简体   繁体   中英

What is the most pythonic way to avoid specifying the same value in a string

message = "hello %s , how are you %s, welcome %s"%("john","john","john")

什么是避免指定“john”3次而是指定一个短语的最pythonic方法。

I wouldn't use % formatting, .format has many advantages. Also % formatting was originally planned to be removed with .format replacing it, although apparently this hasn't actually happened.

A new system for built-in string formatting operations replaces the % string formatting operator. (However, the % operator is still supported; it will be deprecated in Python 3.1 and removed from the language at some later time.) Read PEP 3101 for the full scoop.

>>> "hello {name}, how are you {name}, welcome {name}".format(name='john')
'hello john, how are you john, welcome john'

I prefer the first way since it is explicit, but here is a reason why .format is superior over % formatting

>>> "hello {0}, how are you {0}, welcome {0}".format('john')
'hello john, how are you john, welcome john'
"hello %(name)s , how are you %(name)s, welcome %(name)s" % {"name": "john"}
'hello john, how are you john, welcome john'

This is another way to do this without using format.

This works also:

"hello %s , how are you %s, welcome %s"%tuple(["john"]*3)

or even shorter, without the explicit type cast:

"hello %s , how are you %s, welcome %s"%(("john",)*3)

99% likely you should use .format()

It's unlikely but if you had a series of greetings you could try this:

>>> greetings = ["hello", "how are you", "welcome"]
>>> ", ".join(" ".join((greet, "John")) for greet in greetings)
'hello John, how are you John, welcome John'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM