变量中的Python字符串方法
可以将字符串方法(例如 .rjust())保存在变量中并应用于字符串吗?
看着这里,但无法找到一个解决方案。
例如,不是声明rjust(4, '-')两次,而是在一个变量中编码一次,然后传递给两个字符串?
# Instead of this
print("a".rjust(4, '-'),
"xyz".rjust(4, '-'),
sep="n")
# Something like this?
my_fmt = rjust(4, '-')
print("a".my_fmt,
"xyz".my_fmt,
sep="n")
两者都会导致:
---a
-xyz
回答
为什么不定义一个这样的函数:
def my_fmt(a_string):
return a_string.rjust(4, '-')
print(my_fmt("a"),my_fmt("xyz"), sep="n")
#---a
#-xyz