Truncate beginning of string with str.format

1.9k views Asked by At

I'd like to allign a string to the right but have its beginning be truncated instead of its end.

I tried this:

my_str = '01234567890'
print "{0:>4.4}".format(my_str)

Output:

'0123'

Desidered Output:

'7890'

Is there a way to do this with format or do I have to cut the string before feeding it?

1

There are 1 answers

0
Alnitak42 On

You can use the reverse of the string as input and reverse again the output.

my_str = "01234567890"
new_str = "{:4.4}".format(my_str[::-1])
desired_output = new_str[::-1]

print(my_str[::-1])
print(new_str)
print(desired_output)

Output:

09876543210
0987
7890

Note that a more complex way is described here (StackOverflow question 37974565), which offers a solution if the input string may not be changed (substring, reverse).