Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python 3 equivalent of %s in strings?

I've made some basic progress in python before, nothing more than command land algebra calculators to do math homework, using user-defined functions, inputs, and basic stuff. I've since taken the Python 2 course that codeacademy has, and I'm finding no equivalent of using % and %s for PY3.

I've narrowed it down to having some relation to format() , but that's as far as I could find on Google.

As a beginner, I'd really appreciate a watered down explanation to how to translate this into Python 3:

str1 = "Bob,"
str2 = "Marcey."
print "Hello %s hello %s" % (str1, str2)

EDIT: Also, I'm aware that print("Hello " + str1 + "hello " + str2) would work.

like image 619
Gavin Avatar asked Oct 22 '25 16:10

Gavin


2 Answers

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))
like image 77
Ignacio Vazquez-Abrams Avatar answered Oct 25 '25 05:10

Ignacio Vazquez-Abrams


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.

:)

like image 39
Softy Avatar answered Oct 25 '25 05:10

Softy