Python string percent format

Python String Formatting

Once upon a time, Python introduced percent formatting. It uses «%» as a binary operator to render strings:

>>> drink = "coffee" >>> price = 2.5 >>> message = "This %s costs $%.2f." % (drink, price) >>> print(message) This coffee costs $2.50.

Later in Python 2’s history, a different style was introduced, called simply string formatting (yes, that’s the official name). Its very different syntax makes any Python string a potential template, inserting values through the str.format() method.

>>> template = "This <> costs $." >>> print(template.format(drink, price)) This coffee costs $2.50.

Python 3.6 introduces a third option, called f-strings. This lets you write literal strings, prefixed with an «f» character, interpolating values from the immediate context:

>>> message = f"This costs $." >>> print(message) This coffee costs $2.50.

So. which do you use?

My guidance in a nutshell (with explanations below):

  • Go ahead and master str.format() now. Everything you learn transfers entirely to f-strings, and you’ll sometimes want to use str.format() even in cutting-edge versions of Python.
  • Prefer f-strings when working in a codebase that supports it — meaning, all developers and end-users of the code base are certain to have Python 3.6 or later.
  • Until then, prefer str.format() .
  • Exception: for the logging module, use percent-formatting, even if you’re otherwise using f-strings.
  • Aside from logging , don’t use percent-formatting unless legacy reasons force you to.
Читайте также:  Python insert line to file

«Which should I use?» is a separate question from «which should a Python article use for its code examples?» I use str.format() in this blog, as well as in Powerful Python. That’s because all modern Python versions support it, so I know everyone reading this can use it.

Someday, when Python versions before 3.6 are a distant memory, there will be no reason not to use f-strings. But when that happens, str.format() will still be important. There are string formatting situations where f-strings are awkward at best, and str.format() is well suited. In the meantime, there is a lot of Python code out there using str.format() , which you’ll need to be able to read and understand. That’s why I normally use str.format() in my writing. Conveniently, this also teaches much about f-strings; they are more similar than different, as the formatting codes are nearly identical. str.format() is also the only practical choice for most people reading this, and will be for years still.

You might wonder if the old percent-formatting has any place in modern Python. In fact, it does, due to the logging module. For better or worse, this important module is built on percent-formatting in a deep way. It’s possible to use str.format() in new logging code, but requires special steps; and legacy logging code cannot be safely converted in an automated way. I recommend you just cooperate with the situation, and use percent-formatting for your log messages.

Источник

Python String Interpolation with the Percent (%) Operator

There are a number of different ways to format strings in Python, one of which is done using the % operator, which is known as the string formatting (or interpolation) operator. In this article we’ll show you how to use this operator to construct strings with a template string and variables containing your data.

The % Operator

This way of working with text has been shipped with Python since the beginning, and it’s also known as C-style formatting, as it originates from the C programming language. Another description for it is simple positional formatting.

The % operator tells the Python interpreter to format a string using a given set of variables, enclosed in a tuple, following the operator. A very simple example of this is as follows:

'%s is smaller than %s' % ('one', 'two') 

The Python interpreter substitutes the first occurrence of %s in the string by the given string «one», and the second %s by the string «two». These %s strings are actually placeholders in our «template» string, and they indicate that strings will be placed there.

As a first example, below we demonstrate using the Python REPL how to print a string value and a float value:

>>> print("Mr. %s, the total is %.2f." % ("Jekyll", 15.53)) 'Mr. Jekyll, the total is 15.33.' 

Just like the %s is a placeholder for strings, %f is a placeholder for floating point numbers. The «.2» before the f is what indicates how many digits we want displayed after the decimal point.

These are just two simple examples of what is possible, and a lot more placeholder types are supported. Here is the full list of placeholder types in more detail:

%c

This placeholder represents a single character.

>>> print("The character after %c is %c." % ("B", "C")) The character after B is C. 

Providing more than a single character as the variable here will raise an exception.

%s

This placeholder uses string conversion via str() prior to formatting. So any value that can be converted to a string via str() can be used here.

>>> place = "New York" >>> print("Welcome to %s!" % place) Welcome to New York! 

Here we only have a single element to be used in our string formatting, and thus we’re not required to enclose the element in a tuple like the previous examples.

%i and %d

These placholders represent a signed decimal integer.

>>> year = 2019 >>> print("%i will be a perfect year." % year) 2019 will be a perfect year. 

Since this placeholder expects a decimal, it will be converted to one if a floating point value is provided instead.

%u

This placeholder represents an unsigned decimal integer.

%o

This placeholder represents an octal integer.

>>> number = 15 >>> print("%i in octal is %o" % (number, number)) 15 in octal is 17 
%x

Represents a hexadecimal integer using lowercase letters (a-f).

>>> number = 15 >>> print("%i in hex is %02x" % (number, number)) 15 in hex is 0f 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

By using the «02» prefix in our placeholder, we’re telling Python to print a two-character hex string.

%X

Represents a hexadecimal integer using uppercase letters (A-F).

>>> number = 15 >>> print("%i in hex is %04X" % (number, number)) 15 in hex is 000F 

And like the previous example, by using the «04» prefix in our placeholder, we’re telling Python to print a four-character hex string.

%e

Represents an exponential notation with a lowercase «e».

%E

Represents an exponential notation with an uppercase «e».

%f

Represents a floating point real number.

>>> price = 15.95 >>> print("the price is %.2f" % price) the price is 15.95 
%g

The shorter version of %f and %e .

%G

The shorter version of %f and %E .

The placeholders shown above allow you to format strings by specifying data types in your templates. However, these aren’t the only features of the interpolation operator. In the next subsection we’ll see how we can pad our strings with spaces using the % operator.

Aligning the Output

Up until now we’ve only shown how to format text strings by specifying simple placeholders. With the help of an additional numerical value, you can define the total space that shall be reserved on either side of a variable in the output string.

As an example the value of %10s reserves 10 characters, with the extra spacing on the left side of the placeholder, and a value of %-10s puts any extra space to the right of the placholder. The single padding character is a space, and cannot be changed.

>>> place = "London" >>> print ("%10s is not a place in France" % place) # Pad to the left London is not a place in France >>> print ("%-10s is not a place in France" % place) # Pad to the right London is not a place in France 

Dealing with numbers works in the same way:

>>> print ("The postcode is %10d." % 25000) # Padding on the left side The postcode is 25000. >>> print ("The postcode is %-10d." % 25000) # Padding on the right side The postcode is 25000 . 

Truncating strings and rounding numbers is the counterpart to padding. Have a look at Rounding Numbers in Python in order to learn more about the traps that are hiding here.

Conclusion

In this article we saw how the interpolation (aka formatting) operator is a powerful way to format strings, which allows you to specify data type, floating point precision, and even spacing/padding.

Источник

What to Use string.Format() or Percentage (%) in Python

In this quick tutorial, you’ll get to know which method to choose between format() function or percentage (%) to use for string formatting in Python.

Like the most programming languages, Python too provides a mechanism to format a string. For example, in ‘C’ language, the ‘%’ sign (a.k.a. modulus operator) acts as a format specifier and so does it in Python.

However, Python also has an alternate way for string formatting via the format() function. We will explore the key differences between the ‘%’ operator and the string.format() function in this post.

Python String.Format() Or Percentage (%) for Formatting

Format or percentage for string formatting in Python

Let’s first dig into the percentage (%) sign and see what it does.

If you like to perform some simple string formatting, then try using the ‘%’ operator. It is a pretty old style and will remind you of the C programming language.

Python also adheres to this type of formatting and can format values of all its data types with the % sign.

Check out the below example.

# Percentage (%) demo to format both strings and integer types >>> strHundred = "Hundred" >>> intHundred = 100 >>> "%d means %s" % (intHundred , strHundred) '100 means Hundred'

If you don’t provide an integer type value against the ‘%d’, then Python will raise the TypeError.

The primary problem with the C printf style formatting is that it limits the parameters to be passed. Also, most programmers don’t find as intuitive as the new features in Python.

It was one of the newest features which got introduced in Python 3 for simplifying string formatting. It used a mini-language that provided ease of use and more options.

Please note that its creators also ported it for Python 2.6, one of the most used versions of Python till date.

The format function requires curly brackets as a replacement for % modifiers. It replaces the first occurrence of curly brackets with the value provided as a parameter to the format function.

# String.Format() demo to format strings >>> 'The site <> helped me learn Python.'.format('TechBeamers') 'The site TechBeamers helped me learn Python.'

See another example to discover a potential difference between the string.format() function and the % operator.

Источник

Оцените статью