字符串方法,如.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
与您正在寻找的类似的结果将是以下
def my_fmt(my_str):
return my_str.rjust(4, '-')
print(my_fmt("a"),
my_fmt("xyz"),
sep="n")
不要使用"变量"对于字符串,它将字符串传递给执行所需操作的函数。