Skip to content Skip to sidebar Skip to footer

Truncate Beginning Of String With Str.format

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: '0

Solution 1:

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:

0987654321009877890

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).

Post a Comment for "Truncate Beginning Of String With Str.format"