4

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.

Gavin
  • 143
  • 2
  • 2
  • 10

5 Answers5

8

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))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

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.

:)

Softy
  • 111
  • 8
  • The newer versions of Python do not force writing the index inside the `{0}`. You can use `{}`. – pepr Sep 25 '14 at 11:52
1

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
1

Use f-strings in Python 3

prefix the string with f or F for variables and expressions inserted between curly braces inside the string to be evaluated inline:

str1 = "John Cleese"
str2 = "Michael Palin"
age1 = 73
age2 = 78
print(f"Hello {str1}, hello {str2}, your ages add to {age1 + age2}.")

Note the Python3 brackets in print(). Apparently, string interpolation is faster than the .format() syntax of Python 2.

Dave Everitt
  • 17,193
  • 6
  • 67
  • 97
0

The method you are using is still available in Python 3 (str.mod()). In addition to this you can make use of string formatting in Python. e.g:

print("This is {}".format("sparta"))    #gives output
"This is sparta"

or

a = "Sparta"
b = "King"
print("This is {} and I am its {}".format(a,b))   #gives output
"This is Sparta and I am its King"