我正在尝试为我的Python类编写一个与strip相反的函数。
具体问题是:
有哪些函数可以用来在字符串周围添加空格,以使其达到特定长度?
谢谢!
具体问题是:
有哪些函数可以用来在字符串周围添加空格,以使其达到特定长度?
谢谢!
"%50s World"%("Hello")
"%-50s World"%("Hello")
"%^50s World"%("Hello")
或新潮的
"{0:50s} World".format("Hello")
"{0:>50s} World".format("Hello")
"{0:^50s} World".format("Hello")
"%^*s World"%(50,"Hello")
str.format
函数实现字符串对齐的正确字符为 <
(表示左对齐)和 >
(表示右对齐),而使用 -
则会报错:ValueError: Sign not allowed in string format specifier
。 - Bakurius.center(N)
,其中 N
是你想要的行长度,s
是你的字符串。
例如:>>> "xx".center(10)
' xx '
.center()
是Python字符串方法,作用是在字符串两侧添加空格,使字符串居中对齐。 - Bakuriu