我有一个字符串,像这样:
strTemp='i don\'t want %s repeat the %s variable again %s and again %s'%('aa','aa','aa','aa')
我想要用'aa'替换所有的%s,因此我必须重复多次输入'aa'。该如何告诉程序我想用同一个变量替换所有的%s,这样就不需要多次输入变量。
我有一个字符串,像这样:
strTemp='i don\'t want %s repeat the %s variable again %s and again %s'%('aa','aa','aa','aa')
不建议使用 % 运算符。请改用 str.format
。
strTemp='i don\'t want {0} repeat the {0} variable again {0} and again {0}'.format('aa')
strTemp='i don\'t want %(key)s repeat the %(key)s variable again %(key)s and again %(key)s' % {
'key': 'replacement value',
}
并不一定更好,因为您需要重复四次键,但如果您的替换值很长,或者是带有副作用的计算,您真的不想多做一次,那么这是一个不错的选择。
如果你有很多重复的内容,又不想一遍遍地输入 {0}
或者 %(var)s
,你可以考虑使用一个很少用到的(占位符)字符,然后进行替换,例如:
p='µ µµ µµµ µµµµ µµµµµ {1}'.replace('µ','{0}').format(' muahaha ', 'duh')
或者针对单个替换变量:
strTemp='i don\'t want µ repeat the µ variable again µ and again µ'.replace('µ','aa')
{}
语法是较新且更加时尚的。您可以通过它执行许多%
语法无法实现的操作。我认为%
语法已从 Python 3 中删除,但这可能是错误的。 - zwol{}
明显更强大,但我不明白这怎么导致了对%
的不鼓励。 - Tim%
风格的格式化:http://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting - zwol