Python string formatting LEARNOVITA

Python String Formatting | A Complete Guide For Beginners [ OverView ]

Last updated on 03rd Nov 2022, Artciles, Blog

About author

Nirvi (Python developer )

Nirvi is a Python developer with 7+ years of experience in the Hadoop ecosystem, including Sqoop, Hive, Spark, Scala, HBase, MapReduce, and NoSQL databases, such as HBase, Cassandra, and MongoDB. She spends most of her time researching technology and startups.

(5.0) | 19828 Ratings 2110
    • In this article you will learn:
    • 1.“ Old Style ” String Formatting( Operator).
    • 2.Hey Bob, there’s an error 0xc0ffee.
    • 3.New Style ” String Formatting.
    • 4.Approach to text formatting.
    • 5.Template Strings.
    • 6.Which String Formatting system Should You Use .
    • 7.Formatting Types .
    • 8.For keyword arguments.
    • 9.Conclusion .

“ Old Style ” String Formatting( Operator):

Strings in Python have a unique erected- in operation that can be penetrated with the driver. It lets you do simple positional formatting veritably easily.However, you ’ll fete how it works incontinently, If you ’ve ever worked with a printf- style function inC. There’s a simple illustration >>> ‘ Hello, s ’ name “ Hello, Bob ” I’m using the s format specifier to tell Python where to replace the value of name, which is represented as a string. There are other format specifiers available that let you control the affair format. For illustration, it’s possible to convert figures to hexadecimal memorandum or add whitespace padding to produce well- formatted tables and reports.( See the Python croakers“ printf- style string formatting ”.) Then, you can use the x format specifier to convert an int value to a string and represent it as a hexadecimal number >>> ‘ x ’ error ‘ Bad Coffee ’ The “ old- style ” string formatting syntax changes a bit if you want to do multiple reserves in a single string. Since the driver only takes one argument, you need to wrap the right hand side in a tuple, like this >>> ‘ Hey s, 0xx is an error! ’( name, error) ‘ Hey Bob, there’s an error 0xc0ffee! ’ still, it’s also possible to relate to the variable relief by name in your format string If you pass a mapping to the driver.>>> ‘ Hey( name) s, 0x( errno) x is an error! ’, “ name ” name, “ err ” error}.

Hey Bob there’s an error 0xc0ffee:

You do n’t have to worry about making sure that the order you ’re passing in the values matches the order in which the values are substantiated in the format string. Of course, the strike is that this fashion requires a bit more typing. This was technically supplanted by the “ new style ” formatting in Python 3, which we ’re going to talk about coming.

“ New Style ” String Formatting(str.format):

Python 3 introduced a new way of formatting strings that was later ported back to Python2.7. This “ new style ” string formatting gets rid of the- driver special syntax and makes the syntax for string formatting further regular. Formatting is now controlled by calling. format() on a String object. You can use format() to do simple positional formatting, just like you can with “ old- style ” formatting > ‘ Hello,{} ’. format( name) ‘ Hello, Bob ’ Or, you can relate to your variable reserves by name and use them in the order you want. This is quite an important point as it allows you to rearrange the order of the display without changing the arguments passed to :

  • format() >>> ‘ Hey{ name}, there’s a 0x{ eren ox} error.
  • format( name = name, error = error) .

There’s an error 0xc0ffee:

Now you have to pass a format spec by adding the suffix. Format string syntax has come more important without complicating simple use cases. It pays to read this string formatting mini-language in the Python attestation. In Python 3, this “ new- style ” string formatting is to take priority over- style formatting. While “ old- style ” formatting isn’t emphasized, it isn’t disapproved . It’s still supported in the rearmost performances of Python. According to this discussion on the Python Dev Dispatch List and this issue on the Python Dev Bug Tracker,- formatting is going to be around for a long time to come. Still, the sanctioned Python 3 attestation does n’t recommend “ old- style ” formatting at all or speak veritably hypocritically of it “ The formatting operations described then parade a variety of tricks that lead to a number of common crimes( similar as failing to represent tuples and wordbooks rightly). ” helps to avoid these errors.These options are also more important, flexible and extensible.

Approach to text formatting. ( Source):

This is why I tête-à-tête try to stick with str.format for new law going forward. Starting with Python3.6, there’s another way to format your strings. I ’ll tell you about it in the coming section:

  • 3 String Interpolation/ f- Strings( Python3.6) .
  • Python3.6 added a new string formatting approach called formatted string literals or “ f- strings ”.
  • This new way of formatting strings lets you use Python expressions bedded inside string constants.
  • Here’s a simple illustration to give you a sense of convenience > Hello,{ name}!
  • Hello, Bob!
  • This new formatting syntax is important. Since you can use arbitrary Python expressions, you can also do inline computation with it. Look at this illustration.
  • > a = 5 > b = 10 > f five plus ten is{ a b} and not{ 2 *( a b)}.
  • Formatted string literals is a Python parser mileage that converts f- strings into a series of string constants and expressions. They’re also joined to form the final string.
Python String Formatting

Imagine you have the following hail() function that contains an f- string:

> define salutation( name, question) return f ” Hello,{ name}! How is it{ question}? How’s it going? ” When you disassemble the function and observe what’s going on behind the scenes, you ’ll see that the f- string in the function turns into a commodity analogous to the following>

  • >>> define salutation( name, question) return
  • “ Hello, ” name “!
  • How is it a ” question “?
  • But functionally they’re the same
  • Import Department >dis.dis( hello) 2 0LOAD_CONST 1( ‘ Hello, ’) LOAD_FAST 0( name) 4FORMAT_VALUE 0 6LOAD_CONST 2( “! ’) 14BUILD_STRING 5 16RETURN_VALUE.
  • String literals also support the current format string syntax of the str.format() system.
  • This allows you to break the same formatting problems we bandied in the last two sections.
  • ” Python’s recently formatted string literals are analogous to JavaScript’s template literals added in ES2015. I suppose they’re good enough for Python, and I’ve started using them in my day to day( Python 3) work. You can learn further about formatted string literals in our in- depth Python f- string tutorial.

Template Strings( Standard Library):

Then there’s another tool for string formatting in Python Template Strings. It’s a simpler and less important medium, but in some cases it might be what you ’re looking for. Let’s look at a simple greeting illustration.

  • > from string import template > t = template( ‘ Hey,$ name!

You see then that we need to import the template class from Python’s erected- in string module. Template strings aren’t a core language point, but they’re supplied by the String module in the standard library. Another difference is that template strings don’t allow format specifiers. So to get the former error string illustration to ’ll need to manually convert the int error number to a hex- string :

  • >templ_string = ‘ Hey$ name, there’s a$ error error! ’ >>>
  • template(templ_string).
  • the cover( name = name, error = hex( err))
  • Hey Bob, there’s an error 0xc0ffee!

Which String Formatting system Should You Use:

I completely suppose having so numerous options to format your strings in Python can feel veritably confusing:

Description and operation:

  • The format() system formats the specified value( s) and inserts them inside a string’s placeholder. Placeholders are defined using curled classes{}.
  • Read further about placeholders in the Placeholders section below.
  • The format() system returns a formatted string. syntax ( value1, value2) parameter value parameter description Value1, Value2 needed.
  • One or further values that must be formatted and fitted into the string.
  • Placeholder Placeholders can be linked using named indicator{ price}, numbered indicator{ 0}, or indeed an empty placeholder{}. illustration Using different placeholder values .
  • txt1 = “ My name is{ f name}, I’m{ age} ”.
  • format( “ John ”, 36).
Overview of Python String Formatting

Formatting Types:

  • Right aligns the result( within the available space) .
  • Centre aligns the result( within the available space) = puts the symbol on the far left .
  • Use a else sign to indicate whether the result is positive or negative – For negative values use negative sign only .
  • Use a space to put an redundant space before positive figures( and a disadvantage sign before negative figures).
  • Use a comma as a thousand division .
  • Use an underscore as a thousand .

Converts the value to the corresponding Unicode character d decimal format e:

Scientific format, lowercase e. with e scientific format, uppercase e. with f fix point number format F Fixed point number format, in uppercase format( show inf and nan as INF and NAN) g normal format G Common format( using capital letter E for scientific memorandum) octal format hex format, lower case X hex format, upper case n number format percent format.

For keyword arguments:

  • We’ve used the same illustration from over to show the difference between keywords and positional arguments. Then, rather than just a parameter, we’ve used a crucial- value for the parameter.
  • Videlicet, name = “ Adam ” and blc = 230.2346.
  • Since these parameters are pertained to by their keys as{ name} and{ blc9.3 f}, they’re known as keywords or named arguments.
  • Internally, The placeholder{ name} is replaced by the value of the name – “ Adam ”. Since it doesn’t contain any other format canons, “ Adam ” is placed.
  • For the argument blc = 230.2346, the placeholder{ blc9.3 f} is replaced with the value 230.2346.
  • But before replacing it, as in the former illustration,9.3 f operates on it. It is 230.235. The decimal part is abbreviated after 3 places and the remaining integers are rounded off. Also, leaving two spaces on the left wing is assigned a total range of 9.

Formatting figures with format():

You can format figures using the below format specifiers number formatting type type meaning d decimal integer C biddable unicode characters Binary Format o octal format x hexadecimal format( lower case) X hexadecimal format( upper case) analogous to n ’ d’. except that it uses the current locale setting for the number division E exponential memorandum.( lowercase e) e exponential memorandum( uppercase e) f Displays the fixed point number( dereliction 6) analogous to f’f ’. In addition to displaying ‘ inf ’ as ‘ INF ’ and ‘ nan ’ as ‘ NAN ’ G general format. Integer number to p significant number.( dereliction perfection 6) analogous to ‘ G ’. except switch to ‘ e ’ when the number is large. Percent. Multiply by 100 and put at the end.


It’s a rare operation that does n’t bear manipulating strings, at least to some extent. Python provides a rich set of drivers, functions, and styles for working with strings. Now you know how to Use drivers with strings Access and remove corridor of strings Use erected- in Python functions with characters and strings Use styles to manipulate and modify string data You were also introduced to two other Python objects used to represent raw byte data bytes and bytearray types. String formatting is a veritably important function of any type of programming language. It helps the stoner to understand the affair of the script duly. String formatting in Python can be done in colorful ways, similar as using the ‘’ symbol, format() system, string interpolation,etc. This composition describes Python’s string formatting styles. New Python programmers will be suitable to perform string formatting tasks with ease after reading this composition.

Are you looking training with Right Jobs?

Contact Us

Popular Courses