ale*_*ler 16 python string-formatting
我正在尝试维护/更新/重写/修复一些看起来有点像这样的Python:
variable = """My name is %s and it has been %s since I was born.
My parents decided to call me %s because they thought %s was a nice name.
%s is the same as %s.""" % (name, name, name, name, name, name)
Run Code Online (Sandbox Code Playgroud)
整个脚本都有一些看起来像这样的片段,我想知道是否有一种更简单(更Pythonic?)的方式来编写这段代码.我发现其中一个实例替换了相同的变量大约30次,而且感觉很难看.
围绕(在我看来)丑陋的唯一方法将它分成许多小点?
variable = """My name is %s and it has been %s since I was born.""" % (name, name)
variable += """My parents decided to call me %s because they thought %s was a nice name.""" % (name, name)
variable += """%s is the same as %s.""" % (name, name)
Run Code Online (Sandbox Code Playgroud)
Cat*_*lus 59
请改用字典.
var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }
Run Code Online (Sandbox Code Playgroud)
或者format使用明确的编号.
var = '{0} {0} {0}'.format('look_at_meeee')
Run Code Online (Sandbox Code Playgroud)
好吧,或者format使用命名参数.
var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')
Run Code Online (Sandbox Code Playgroud)
使用格式字符串:
>>> variable = """My name is {name} and it has been {name} since..."""
>>> n = "alex"
>>>
>>> variable.format(name=n)
'My name is alex and it has been alex since...'
Run Code Online (Sandbox Code Playgroud)
{}中的文本可以是描述符或索引值.
另一个奇特的技巧是使用字典结合**运算符定义多个变量.
>>> values = {"name": "alex", "color": "red"}
>>> """My name is {name} and my favorite color is {color}""".format(**values)
'My name is alex and my favorite color is red'
>>>
Run Code Online (Sandbox Code Playgroud)
Python 3.6 引入了一种更简单的方法来格式化字符串。您可以在PEP 498 中获得有关它的详细信息
>>> name = "Sam"
>>> age = 30
>>> f"Hello, {name}. You are {age}."
'Hello, Sam. You are 30.'
Run Code Online (Sandbox Code Playgroud)
它还支持运行时评估
>>>f"{2 * 30}"
'60'
Run Code Online (Sandbox Code Playgroud)
它也支持字典操作
>>> comedian = {'name': 'Tom', 'age': 30}
>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."
The comedian is Tom, aged 30.
Run Code Online (Sandbox Code Playgroud)
使用新的string.format:
name = 'Alex'
variable = """My name is {0} and it has been {0} since I was born.
My parents decided to call me {0} because they thought {0} was a nice name.
{0} is the same as {0}.""".format(name)
Run Code Online (Sandbox Code Playgroud)
>>> "%(name)s %(name)s hello!" % dict(name='foo')
'foo foo hello!'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32353 次 |
| 最近记录: |