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?
source share