omer bach
omer bach

Reputation: 2395

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")

What is the most pythonic way to avoid specifying "john" 3 times and instead to specify one phrase.

Upvotes: 8

Views: 311

Answers (4)

hendrik
hendrik

Reputation: 2042

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)

Upvotes: 3

jamylak
jamylak

Reputation: 133584

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'

Upvotes: 24

Rusty Rob
Rusty Rob

Reputation: 17183

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'

Upvotes: 1

spicavigo
spicavigo

Reputation: 4224

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

Upvotes: 11

Related Questions