2009-08-04 141 views
85

當相同的值多次插入我有這種形式格式化的字符串

s='arbit' 
string='%s hello world %s hello world %s' %(s,s,s) 

的字符串的所有%S在串具有相同的值(即多個)。 有沒有更好的書寫方式? (除了列明的三個次)

+0

Duplicate:http://stackoverflow.com/questions/543399/python-string-formatting – bignose 2010-03-23 13:07:35

+2

這個`%`字符串操作符將會「在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

+2

@Cawas我知道這很晚了,但我喜歡用`str.format()`。例如:`query =「SELECT * FROM {named_arg}」; query.format(** kwargs)`,其中`query`是格式字符串,`kwargs`是一個字典,其中的鍵與格式字符串中的`named_arg`匹配。 – Edwin 2012-05-14 02:36:02

回答

154

您可以使用advanced string formatting,可以在Python 2.6和Python 3.x的:

incoming = 'arbit' 
result = '{0} hello world {0} hello world {0}'.format(incoming) 
35
incoming = 'arbit' 
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming} 

你可能喜歡有這樣的念想獲得一個認識:String Formatting Operations

13

可以利用格式的字典類型:

s='arbit' 
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,} 
11

取決於你的意思是什麼更好。如果您的目標是刪除冗餘,這將起作用。

s='foo' 
string='%s bar baz %s bar baz %s bar baz' % (3*(s,)) 
3
>>> s1 ='arbit' 
>>> s2 = 'hello world '.join([s]*3) 
>>> print s2 
arbit hello world arbit hello world arbit 
0

Fstrings

如果您正在使用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實際上是更快的映射。