Python 2.6引入了该str.format()方法,其语法与现有%运算符略有不同.哪种情况更好,哪种情况更好?
以下使用每种方法并具有相同的结果,那么有什么区别?
#!/usr/bin/python
sub1 = "python string!"
sub2 = "an arg"
a = "i am a %s" % sub1
b = "i am a {0}".format(sub1)
c = "with %(kwarg)s!" % {'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)
print a # "i am a python string!"
print b # "i am a python string!"
print c # "with an arg!"
print d # "with an arg!"
Run Code Online (Sandbox Code Playgroud)此外,何时在Python中发生字符串格式化?例如,如果我的日志记录级别设置为HIGH,我仍然会执行以下%操作吗?如果是这样,有没有办法避免这种情况?
log.debug("some debug info: %s" % some_info)
Run Code Online (Sandbox Code Playgroud)我只想要固定宽度的文本列,但字符串都填充正确,而不是左边!!?
sys.stdout.write("%6s %50s %25s\n" % (code, name, industry))
Run Code Online (Sandbox Code Playgroud)
产生
BGA BEGA CHEESE LIMITED Food Beverage & Tobacco
BHP BHP BILLITON LIMITED Materials
BGL BIGAIR GROUP LIMITED Telecommunication Services
BGG BLACKGOLD INTERNATIONAL HOLDINGS LIMITED Energy
Run Code Online (Sandbox Code Playgroud)
但我们想要
BGA BEGA CHEESE LIMITED Food Beverage & Tobacco
BHP BHP BILLITON LIMITED Materials
BGL BIGAIR GROUP LIMITED Telecommunication Services
BGG BLACKGOLD INTERNATIONAL HOLDINGS LIMITED Energy
Run Code Online (Sandbox Code Playgroud) 在Python中,编写它是很繁琐的:
print "foo is" + bar + '.'
Run Code Online (Sandbox Code Playgroud)
我可以在Python中做这样的事吗?
print "foo is #{bar}."
ruby python language-comparisons string-formatting string-interpolation
这是在Python中格式化字符串的两种非常流行的方法.一个是使用dict:
>>> 'I will be %(years)i on %(month)s %(day)i' % {'years': 21, 'month': 'January', 'day': 23}
'I will be 21 on January 23'
Run Code Online (Sandbox Code Playgroud)
而另一个使用简单tuple:
>>> 'I will be %i on %s %i' % (21, 'January', 23)
'I will be 21 on January 23'
Run Code Online (Sandbox Code Playgroud)
第一个是更具可读性,但第二个更快写.我实际上模糊地使用它们.
每个人的利弊是什么?关于性能,可读性,代码优化(其中一个转换为另一个?)以及您认为有用的任何其他内容.
如何使用变量格式化变量?
cart = {"pinapple": 1, "towel": 4, "lube": 1}
column_width = max(len(item) for item in items)
for item, qty in cart.items():
print "{:column_width}: {}".format(item, qty)
> ValueError: Invalid conversion specification
Run Code Online (Sandbox Code Playgroud)
要么
(...):
print "{:"+str(column_width)+"}: {}".format(item, qty)
> ValueError: Single '}' encountered in format string
Run Code Online (Sandbox Code Playgroud)
但是,我能做的是首先构造格式化字符串然后格式化它:
(...):
formatter = "{:"+str(column_width)+"}: {}"
print formatter.format(item, qty)
> lube : 1
> towel : 4
> pinapple: 1
Run Code Online (Sandbox Code Playgroud)
然而,看起来很笨拙.是不是有更好的方法来处理这种情况?
EDITED
我必须使用字典中的值格式化字符串,但字符串已包含大括号.例如:
raw_string = """
DATABASE = {
'name': '{DB_NAME}'
}
"""
Run Code Online (Sandbox Code Playgroud)
但是,当然,raw_string.format(my_dictionary)KeyErro的结果.
有没有办法使用不同的符号.format()?
这不是重复的如何在python字符串中打印文字大括号字符并在其上使用.format?因为我需要保持大括号,并使用不同的分隔符.format.
String格式表达式:
'This is %d %s example!' % (1, 'nice')
Run Code Online (Sandbox Code Playgroud)
字符串格式化方法调用
'This is {0} {1} example!'.format(1, 'nice')
Run Code Online (Sandbox Code Playgroud)
我个人更喜欢方法调用(第二个例子)的可读性,但由于它是新的,因此有可能随着时间的推移,这些中的一个或另一个可能会被弃用.您认为哪个不太可能被弃用?
我在这里读到,计划最终使这个["".format()]成为字符串格式化的唯一API,并开始在Python 3.1中弃用%运算符.
我尝试使用Python 3.1,3.2和3.3的%语法,它正在工作.那么是否仍有计划在未来版本中从Python中删除%语法,或者我可以自由使用它吗?
伙计我是初学者,我正在尝试(稍微失败)自学编程和编写代码,所以你的帮助非常感谢
favorite_foods = {'Armon' : 'wings',
'Dad' : 'kabob',
'Joe' : 'chinese',
'mom' : 'veggies',
'Das' : 'addas_polo',
'Rudy' : 'free_food',
'Nick' : 'hotnspicy',
'layla' : 'fries',
'Shaun' : 'sugar',
'Zareen' : 'cookie',
'Elahe' : 'hotdogs'}
print(favorite_foods)
print "Whose favorite food do you want to know"
person = raw_input()
fav = (favorite_foods[person])
print "%r favorite food is %s" (person, fav)
Run Code Online (Sandbox Code Playgroud)
我一直收到错误:
TypeError: 'str' object is not callable.
Run Code Online (Sandbox Code Playgroud)
你能告诉我我的代码有什么问题吗?对于初学者,你怎么知道要修复什么?
谢谢
python ×10
string ×2
cheetah ×1
deprecated ×1
format ×1
logging ×1
performance ×1
printf ×1
python-3.x ×1
ruby ×1
syntax ×1
typeerror ×1