How to make this simple string function "pythonic"

Coming from the C / C ++ world and being Python newb, I wrote this simple string function that takes an input string (guaranteed as ASCII) and returns the last four characters. If the number is less than four characters, I want to fill the leading position with the letter "A". (this is not an exercise, but a valuable part of another complex function)

There are dozens of ways to do this, from brute force to simple, elegant. My approach below, although functional, did not seem "Pythonic".

NOTE. I am currently using Python 2.6 - and performance is NOT a problem. The input lines are short (2-8 characters), and I call this function just a few thousand times.

def copyFourTrailingChars(src_str): four_char_array = bytearray("AAAA") xfrPos = 4 for x in src_str[::-1]: xfrPos -= 1 four_char_array[xfrPos] = x if xfrPos == 0: break return str(four_char_array) input_str = "7654321" print("The output of {0} is {1}".format(input_str, copyFourTrailingChars(input_str))) input_str = "21" print("The output of {0} is {1}".format(input_str, copyFourTrailingChars(input_str))) 

Output:

 The output of 7654321 is 4321 The output of 21 is AA21 

Offers from Pythoneers?

+5
source share
5 answers

I would use a simple slice and then str.rjust() to justify the result, using A as fillchar . Example -

 def copy_four(s): return s[-4:].rjust(4,'A') 

Demo -

 >>> copy_four('21') 'AA21' >>> copy_four('1233423') '3423' 
+27
source

You can simply add four inquiry characters 'A' in front of the original line, then take the last four characters:

 def copy_four(s): return ('AAAA'+s)[-4:] 

It is simple enough!

+5
source

How about something with string formatting?

 def copy_four(s): return '{}{}{}{}'.format(*('A'*(4-len(s[-4:])) + s[-4:])) 

Result:

 >>> copy_four('abcde') 'bcde' >>> copy_four('abc') 'Aabc' 

Here's a nicer, more canonical option:

 def copy_four(s): return '{:A>4}'.format(s[-4:]) 

Result:

 >>> copy_four('abcde') 'bcde' >>> copy_four('abc') 'Aabc' 
+4
source

You can use slicing to get the last 4 characters, then repeat the string (operator * ) and concatenation ( + operator) as shown below:

 def trailing_four(s): s = s[-4:] s = 'A' * (4 - len(s)) + s return s 
+3
source

You can try this

 def copy_four_trailing_chars(input_string) list_a = ['A','A','A','A'] str1 = input_string[:-4] if len(str1) < 4: str1 = "%s%s" % (''.join(list_a[:4-len(str1)]), str1) return str1 
+3
source

All Articles