Python 3 string formatting as of 2019 (latest standard)


#1

What is the latest Python 3 string formatting style that is used?

Where may I find a list of the changes from Python 2.0?

Thanks.


#2

Not sure there is a latest standard, but there has been a new format introduced in Python 3.6, f-strings. Previous to that we had the modulo format, %s, &c. and later in Python 2 the .format method was introduced.

To compare the two major versions, search for what's new in Python 3 and it should turn up some useful comparisons.

The ones we deal with the most are,

  • print - in Python 2, this is a construct but in 3 it is a function.
  • iterators - in Python 2 iterators returned a list but in 3 they return an iterator object.
  • raw_input - from Python 2 is obsolete in 3, and has been revised to use input.

You’ll find other differences, of course, not the least of which is how each version works with character data. In python 3 all character data is unicode.

If you are working with Python 3.6 or above, f-string is very similar to string interpolation in ES6 and Ruby where the placeholders contain their interpolated variable.

f"{var1} lorem ipsum {var2}"     # Python 3.6

which compares directly to,

"${var1} lorem ipsum ${var2}"    // ES6

"#{var1} lorem ipsum #{var2}"    # Ruby

#3

May I also write it with the .format?

Ex.
print(“This line of code contains {var 3} and {var 4}”.format(variable1, variable2))


#4

With str.format we can use keywords but they get defined in the arguments list. We cannot interpolate them like f-strings.

print("{a} and {b} are interpolated values.".format(a=var1, b=var2))