当相同的值多次插入我有这种形式格式化的字符串
s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)
的字符串的所有%S在串具有相同的值(即多个)。 有没有更好的书写方式? (除了列明的三个次)
当相同的值多次插入我有这种形式格式化的字符串
s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)
的字符串的所有%S在串具有相同的值(即多个)。 有没有更好的书写方式? (除了列明的三个次)
您可以使用advanced string formatting,可以在Python 2.6和Python 3.x的:
incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)
incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}
你可能喜欢有这样的念想获得一个认识:String Formatting Operations。
可以利用格式的字典类型:
s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}
取决于你的意思是什么更好。如果您的目标是删除冗余,这将起作用。
s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))
>>> s1 ='arbit'
>>> s2 = 'hello world '.join([s]*3)
>>> print s2
arbit hello world arbit hello world arbit
如果您正在使用Python 3.6+
,您可以利用新的所谓f-strings
它代表格式化字符串,它可以通过在一开头添加字符f
使用字符串将其识别为f-string。
price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!
使用F-字符串的主要好处是,它们更易读,可以更快,并提供更好的性能:
来源熊猫的每个人:Python的数据分析,丹尼尔Y.陈
毫无疑问,新f-strings
可读性更强,因为你不必重新映射串,b尽管正如前面所述的报价中所述,它是否更快?
price = 123
name = "Jerry"
def new():
x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"
def old():
x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)
import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776 #new
> 5.861819514350163 #old
运行10万次测试的似乎新f-strings
实际上是更快的映射。
Duplicate:http://stackoverflow.com/questions/543399/python-string-formatting – bignose 2010-03-23 13:07:35
这个`%`字符串操作符将会“在Python 3.1上被弃用,并在某个时候被删除”http://docs.python .org/release/3.0.1/whatsnew/3.0.html#pep-3101-a-new-approach-to-string-formatting现在我想知道什么是最适合版本兼容性和安全性的方式。 – cregox 2010-04-30 00:34:58
@Cawas我知道这很晚了,但我喜欢用`str.format()`。例如:`query =“SELECT * FROM {named_arg}”; query.format(** kwargs)`,其中`query`是格式字符串,`kwargs`是一个字典,其中的键与格式字符串中的`named_arg`匹配。 – Edwin 2012-05-14 02:36:02