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.
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.
"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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With