What is the Python 3 equivalent of %s in strings?
What is the Python 3 equivalent of %s in strings?
str.__mod__()
continues to work in 3.x, but the new way of performing string formatting using str.format()
is described in PEP 3101, and has subsequently been backported to recent versions of 2.x.
print(Hello %s hello %s % (str1, str2))
print(Hello {} hello {}.format(str1, str2))
This should work as intended:
str1 = Bob,
str2 = Marcey.
print(Hello {0} hello {1}.format(str1, str2))
While the use of % to format strings in Python 3 is still functional, it is recommended to use the new string.format(). It is more powerful and % will be removed from the language at some point.
Go on the Python website to see changes from Python 2.7 to Python 3 and the documentation contains everything you need.
🙂
What is the Python 3 equivalent of %s in strings?
The %
operator is not related to print
; rather, it is a string operator. Consider this valid Python 2.x code:
x = %s %s % (a, b)
print x
Nearly identical code works in Python 3:
x = %s %s % (a, b)
print(x)
Your attempt would be correctly written as
print(%s %s % (a, b))
The %
operator is analogous to the C function sprintf
, not printf
.