5

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?

5 Answers 5

27

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'
Sign up to request clarification or add additional context in comments.

4 Comments

@VigneshKalai - Wow! That is amazing! Sure am glad I asked!
@SMGreenfield I did not answer that it was anand s kumar :)
@anand : you can also pass the string directly as a parameter, which makes it more intuitive.
@kmario23 I guessed you are talking about the Demo , yea you are correct there. Thank you, fixed it.
5

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!

1 Comment

I LOVE this -- so clever -- totally out-of-the-box thinking!
4

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'

2 Comments

your canonical version looks real cool -- but being a Python newb I'm having a hard time understanding the syntactical trick(s) you used, particularly {:A>4}. Can you describe what you've done here?
@SMGreenfield - that right-aligns > the sliced string s[-4:] in a field {} with a maximum length of 4 characters, and fills in any strings that are too short with the character A.
3

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

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

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.