如何使这个简单的字符串函数"pythonic"

SMG*_*eld 5 python string

来自C/C++世界并且是一个Python newb,我写了这个简单的字符串函数,它接受一个输入字符串(保证是ASCII)并返回最后四个字符.如果少于四个字符,我想用字母"A"填充主要位置.(这不是练习,而是另一个复杂功能的重要部分)

从蛮力到简单到优雅,有很多方法可以做到这一点.下面我的方法,虽然功能,但似乎不是"Pythonic".

注意:我目前正在使用Python 2.6 - 性能不是问题.输入字符串很短(2-8个字符),我只调用这个函数几千次.

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)))
Run Code Online (Sandbox Code Playgroud)

输出是:

The output of 7654321 is 4321
The output of 21 is AA21
Run Code Online (Sandbox Code Playgroud)

Pythoneers的建议?

Ana*_*mar 27

我会使用简单的切片,然后str.rjust()使用Aas 右对齐结果fillchar.示例 -

def copy_four(s):
    return s[-4:].rjust(4,'A')
Run Code Online (Sandbox Code Playgroud)

演示 -

>>> copy_four('21')
'AA21'
>>> copy_four('1233423')
'3423'
Run Code Online (Sandbox Code Playgroud)


Alf*_*ang 5

您可以在原始字符串之前简单地添加四个标记'A'字符,然后取四个字符结尾:

def copy_four(s):
    return ('AAAA'+s)[-4:]
Run Code Online (Sandbox Code Playgroud)

这很简单!