开发者

Output formatting in Python: replacing several %s with the same variable

I'm trying to maintain/update/rewrite/fix a bit of Python that looks a bit like this:

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)

There are little snippets that look like this all over the script, and I was wondering whether there's a simpler (more Pythonic?) way to write this code. I've found one instance of this that replaces the same variable about 30 times, and开发者_Python百科 it just feels ugly.

Is the only way around the (in my opinion) ugliness to split it up into lots of little bits?

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)


Use a dictionary instead.

var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }

Or format with explicit numbering.

var = '{0} {0} {0}'.format('look_at_meeee')

Well, or format with named parameters.

var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')


Python 3.6 has introduced a simpler way to format strings. You can get details about it in PEP 498

>>> name = "Sam"
>>> age = 30
>>> f"Hello, {name}. You are {age}."
'Hello, Sam. You are 30.'

It also support runtime evaluation

>>>f"{2 * 30}"
'60'

It supports dictionary operation too

>>> comedian = {'name': 'Tom', 'age': 30}
>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."
 The comedian is Tom, aged 30.


Use formatting strings:

>>> 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...'

The text within the {} can be a descriptor or an index value.

Another fancy trick is to use a dictionary to define multiple variables in combination with the ** operator.

>>> 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'
>>>


Use the new 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)


>>> "%(name)s %(name)s hello!" % dict(name='foo')
'foo foo hello!'


You could use named parameters. See examples here


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)


have a look at Template Strings


If you are using Python 3, than you can also leverage, f-strings

myname = "Test"
sample_string = "Hi my name is {name}".format(name=myname)

to

sample_string = f"Hi my name is {myname}"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜