Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this simple string function "pythonic"

Tags:

python

string

Coming from the C/C++ world and being a Python newb, I wrote this simple string function that takes an input string (guaranteed to be ASCII) and returns the last four characters. If there’s less than four characters, I want to fill the leading positions with the letter ‘A'. (this was not an exercise, but a valuable part of another complex function)

There are dozens of methods of doing this, from brute force, to simple, to elegant. My approach below, while functional, didn’t seem "Pythonic".

NOTE: I’m presently using Python 2.6 — and performance is NOT an issue. The input strings are short (2-8 characters), and I call this function only 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)))

The output is:

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

Suggestions from Pythoneers?

like image 401
SMGreenfield Avatar asked Sep 16 '15 06:09

SMGreenfield


2 Answers

I would use simple slicing and then str.rjust() to right 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'
like image 52
Anand S Kumar Avatar answered Sep 30 '22 17:09

Anand S Kumar


You can simple adding four sentinel 'A' character before the original string, then take the ending four characters:

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

That's simple enough!

like image 43
Alfred Huang Avatar answered Sep 30 '22 17:09

Alfred Huang