使用str.format截断字符串的开头 [英] Truncate beginning of string with str.format

查看:170
本文介绍了使用str.format截断字符串的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在右边插入一个字符串,但其开头应被截断而不是结尾.

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

我尝试过:

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

输出:

'0123'

所需的输出:

'7890'

有没有办法用format做到这一点,或者我必须在送入弦线之前先剪掉弦线?

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

推荐答案

您可以将字符串的反向用作输入,然后再次反向输出.

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)

输出:

09876543210
0987
7890

请注意,在此处(StackOverflow问题37974565 ),如果输入的字符串不能更改(子字符串,反向),则可以提供解决方案.

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

这篇关于使用str.format截断字符串的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆