Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 493
omer bach Avatar asked Aug 12 '12 10:08

omer bach


People also ask

What is %d and %f in Python?

Answer. In Python, string formatters are essentially placeholders that let us pass in different values into some formatted string. The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point.

What does {: 3f mean in Python?

"f" stands for floating point. The integer (here 3) represents the number of decimals after the point. "%. 3f" will print a real number with 3 figures after the point. – Kefeng91.

What is the string .format method used for in Python?

Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.

How do you use %s in Python?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.


2 Answers

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'
like image 146
jamylak Avatar answered Sep 23 '22 01:09

jamylak


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

like image 40
spicavigo Avatar answered Sep 25 '22 01:09

spicavigo