Read in Paragraph as One Element Python
Python f-strings are impressive!
Did you lot know yous tin use f-strings to cord format almost anything in Python? You lot can use them to format floats, multiline strings, decimal places, objects and even use if-else conditionals within them.
In this post, I'll show you lot at least 73 examples on how to format strings using Python 3's f-strings. Yous'll see the many ways y'all can take reward of this powerful feature.
By the end of this guide, you'll take mastered:
- how to employ f string to format float numbers
- how to format multiline string
- how to ascertain decimal places in a f-cord
- how to fix invalid syntax errors such as "syntaxerror: f-string: unmatched '['" or f-cord: unmatched '('
- how to use if else argument in a f-cord
- basic cord interpolation formatting using f-strings
- how to impress f-strings
- how to finer add padding using fstring
Permit's get!
Table of Contents
- What Are Python 3'due south F-Strings - a.k.a Literal String Interpolation?
- How to Format Strings in Python 3 - The Basics
- Limitations
- How to Format an Expression
- How to Employ F-Strings to Debug Your Code
- How to Format a Multiline F-String (Dealing with New Lines and Variables)
- How to Fix F-String'south Invalid Syntax Mistake
- How to Set "formatting a regular string which could exist a f-string"
- How to Format Numbers in Dissimilar Bases
- How to Print Formatted Objects With F-Strings
- How to Use F-Strings to Format a Float
- How to Format a Number every bit Percentage
- How to Justify or Add Padding to a F-String
- How to Escape Characters With f-string
-
How to Add a G Separator
15.1. How to Format a Number With Commas as Decimal Separator
15.2. How to Format a Number With Spaces as Decimal Separator
- How to Format a Number in Scientific Notation (Exponential Notation)
- Using
if-else
Conditional in a F-String - How to Use F-Cord With a Lexicon
- How to Concatenate F-Strings
- How to Format a Engagement With F-String
- How to Add Leading Zeros
- Decision
What Are Python F-Strings - a.k.a Literal String Interpolation?
String formatting has evolved quite a bit in the history of Python. Before Python 2.6, to format a string, one would either use the %
operator, or string.Template
module. Some fourth dimension later, the str.format
method came forth and added to the language a more flexible and robust way of formatting a cord.
Old string formatting with %
:
>>> msg = 'hello world' >>> 'msg: %s' % msg 'msg: hello earth'
Using string.format
:
>>> msg = 'how-do-you-do world' >>> 'msg: {}'.format(msg) 'msg: hello world'
To simplify formatting fifty-fifty further, in 2015, Eric Smith proposed the PEP 498 -- Literal Cord Interpolation , a new way to format a string for python 3.
PEP 498 presented this new string interpolation to be a simple and easy to apply alternative to str.format
. The only thing required is to put a 'f' before a string. And if yous're new to the language, that's what f in Python means, it's a new syntax to create formatted strings.
Using f-strings:
>>> msg = 'hello world' >>> f'msg: {msg}' 'msg: hello world'
And that was it! No need to apply str.format
or %
. All the same, f-strings don't replace str.format
completely. In this guide I'll show yous an example where they are not suitable.
How to Format Strings in Python 3 - The Basics
Equally I have shown in the previous section, formatting strings in python using f-strings is quite straightforward. The sole requirement is to provide it a valid expression. f-strings can also start with majuscule F
and you lot tin can combine with raw strings to produce a formatted output. However, you cannot mix them with bytes b""
or "u"
.
>>> book = "The dog guide" >>> num_pages = 124 >>> f"The book {volume} has {num_pages} pages" 'The book The domestic dog guide has 124 pages' >>> F"The volume {book} has {num_pages} pages" 'The volume The canis familiaris guide has 124 pages' >>> impress(Fr"The book {book} has {num_pages} pages\n") The volume The domestic dog guide has 124 pages\n >>> print(FR"The volume {volume} has {num_pages} pages\n") The volume The dog guide has 124 pages\n >>> print(f"The book {volume} has {num_pages} pages\n") The book The dog guide has 124 pages
And that'south pretty much it! In the adjacent section, I'll show you lot several examples of everything you tin exercise - and cannot do - with f-strings.
Limitations
Even though f-strings are very convenient, they don't replace str.format
completely. f-strings evaluate expressions in the context where they appear. According the the PEP 498 , this ways the expression has total access to local and global variables. They're as well an expression evaluated at runtime. If the expression used inside the { <expr> }
cannot exist evaluated, the interpreter will raise an exception.
>>> f"{name}" --------------------------------------------------------------------------- NameError Traceback (most contempo call last) <ipython-input-1-f0acc441190f> in <module> ----> 1 f"{name}" NameError: proper name 'name' is not defined
This is not a problem for the str.format
method, equally y'all can ascertain the template cord and then telephone call .format
to pass on the context.
>>> s = "{proper noun}" >>> s.format(name="Python") 'Python' >>> impress(s) {proper noun}
Another limitation is that yous cannot use inline comments inside a f-cord.
>>> f"My name is {name #name}!" File "<ipython-input-37-0ae1738dd871>", line ane f"My name is {name #name}!" ^ SyntaxError: f-string expression office cannot include '#'
How to Format an Expression
If y'all don't want to define variables, y'all tin use literals inside the brackets. Python will evaluate the expression and brandish the concluding result.
>>> f"4 * iv is {4 * 4}" 'iv * 4 is 16'
Or if you lot prefer...
>>> n = 4 >>> f"iv * 4 is {n * due north}" 'four * iv is xvi'
How to Use F-Strings to Debug Your Code
I of almost frequent usages of f-cord is debugging. Earlier Python 3.eight, many people would do hello = 42; f"hullo = {hello}"
, merely this is very repetitive. As a event, Python 3.8 brought a new feature. You lot can re-write that expression every bit f"{how-do-you-do=}"
and Python volition brandish hello=42
. The following example illustrates this using a role, but the principle is the same.
>>> def magic_number(): ...: return 42 ...: >>> f"{magic_number() = }" 'magic_number() = 42'
How to Format a Multiline F-String (Dealing with New Lines and Variables)
You can use the newline graphic symbol \n
with f-strings to print a string in multiple lines.
>>> multi_line = (f'R: {colour["R"]}\nG: {colour["G"]}\nB: {color["B" ...: ]}\north') >>> multi_line 'R: 123\nG: 145\nB: 255\due north' >>> print(multi_line) R: 123 Grand: 145 B: 255
Equally an alternative, yous can use triple quotes to correspond the multiline string with variables. It non only allows you to add line breaks, it's also possible to add together TAB
.
>>> other = f"""R: {color["R"]} ...: One thousand: {color["1000"]} ...: B: {colour["B"]} ...: """ >>> impress(other) R: 123 G: 145 B: 255
Case with TAB
s.
>>> other = f''' ...: this is an example ...: ...: ^Iof color {color["R"]} ...: ...: ''' >>> other '\nthis is an example\northward\n\tof color 123\n \n' >>> impress(other) this is an example of colour 123 >>>
How to Fix F-String'due south Invalid Syntax Error
If not used correctly, f-strings tin heighten a SyntaxError
. The about common cause is using double-quotes within a double quoted f-string. The same is likewise true for single quotes.
>>> color = {"R": 123, "G": 145, "B": 255} >>> f"{color["R"]}" File "<ipython-input-43-1a7f5d512400>", line 1 f"{colour["R"]}" ^ SyntaxError: f-string: unmatched '[' # using but single quotes >>> f'{color['R']}' File "<ipython-input-44-3499a4e3120c>", line ane f'{colour['R']}' ^ SyntaxError: f-string: unmatched '['
This error not just happens with '['
, but also '('
. The cause is the same, it happens when you close a quote prematurely.
>>> print(f"price: {format(circular(12.345), ",")}") File "<ipython-input-two-1ae6f786bc4d>", line 1 impress(f"price: {format(round(12.345), ",")}") ^ SyntaxError: f-cord: unmatched '('
To fix that, you need to use single quotes.
>>> print(f"price: {format(circular(12.345), ',')}") price: 12 >>> color = {"R": 123, "G": 145, "B": 255} >>> f"{color['R']}" '123' >>> f'{colour["R"]}' '123'
Some other mutual case is to apply f-strings in older versions of Python. f-strings were introduced in Python 3.six. If you utilize information technology in an older version, the interpreter will raise a SyntaxError: invalid syntax
.
>>> f"this is an old version" File "<stdin>", line i f"this is an old verion" ^ SyntaxError: invalid syntax
If you see invalid syntax
, brand sure to double check the Python version you are running. In my example, I tested in on Python 2.seven, and y'all can observe the version by calling sys.version
.
>>> import sys; print(sys.version) 2.7 .18 (default, Apr twenty 2020, 19:27:10) [GCC eight.3 .0]
How to Ready "formatting a regular cord which could be a f-string"
This error happens considering pylint detects the old style of formatting string such as using %
or the str.format
method.
C0209: Formatting a regular cord which could exist a f-cord (consider-using-f-string)
To fix that you tin can either:
- supplant the onetime formatting method with a f-string
- ignore the pylint error using
In this postal service, I explicate how to fix this result footstep-past-step.
Replacing with f-strings
The post-obit examples illustrate how to catechumen former method to f-string.
>>> ip_address = "127.0.0.i" # pylint complains if nosotros utilize the methods below >>> "http://%south:8000/" % ip_address 'http://127.0.0.one:8000/' >>> "http://{}:8000/".format(ip_address) 'http://127.0.0.i:8000/' # Supercede it with a f-string >>> f"http://{ip_address}:8000/" 'http://127.0.0.one:8000/'
Disable pylint
Alternatively, you tin disable pylint
by specifying the "disable" flag with the error code.
>>> ip_address = "127.0.0.one" # pylint complains if we use the methods below, so we tin can disable them >>> "http://%s:8000/" % ip_address # pylint: disable=C0209 'http://127.0.0.one:8000/' >>> "http://{}:8000/".format(ip_address) # pylint: disable=C0209 'http://127.0.0.1:8000/'
Another way of disabling that error is to add together it to the .pylintrc
file.
# .pylintrc disable= ... consider-using-f-string, ...
There'southward yet another way of disabling it, which is by placing a annotate at the top of the file, like and then:
# pylint: disable=consider-using-f-string def your_function(fun): """Your lawmaking below""" ...
How to Format Numbers in Different Bases
f-strings also let you lot to display an integer in dissimilar bases. For example, you tin display an int
every bit binary without converting it by using the b
option.
>>> f'{seven:b}' '111'
In summary, you can use f-strings to format:
-
int
to binary -
int
to hex -
int
to octal -
int
to HEX (where all chars are capitalized)
The post-obit example uses the padding feature and the base formatting to create a tabular array that displays an int
in other bases.
>>> bases = { "b": "bin", "o": "oct", "10": "hex", "X": "HEX", "d": "decimal" } >>> for n in range(1, 21): ...: for base of operations, desc in bases.items(): ...: print(f"{due north:5{base}}", end=' ') ...: impress() 1 one 1 1 1 ten two two 2 2 11 3 3 3 three 100 4 four iv 4 101 five 5 5 5 110 half dozen 6 6 6 111 vii seven 7 vii yard 10 8 8 8 1001 11 9 9 9 1010 12 a A 10 1011 13 b B xi 1100 14 c C 12 1101 15 d D 13 1110 16 eastward Eastward 14 1111 17 f F 15 10000 xx 10 10 16 10001 21 11 11 17 10010 22 12 12 18 10011 23 thirteen 13 19 10100 24 14 14 20
How to Print Formatted Objects With F-Strings
You lot can print custom objects using f-strings. By default, when you laissez passer an object instance to a f-string, it will display what the __str__
method returns. Withal, you tin also employ the explicit conversion flag to brandish the __repr__
.
!r - converts the value to a string using repr(). !south - converts the value to a cord using str().
>>> course Colour: def __init__(self, r: float = 255, g: float = 255, b: float = 255 ): self.r = r cocky.g = g self.b = b def __str__(self) -> str: return "A RGB colour" def __repr__(self) -> str: return f"Colour(r={self.r}, g={self.thousand}, b={self.b})" >>> c = Colour(r=123, g=32, b=255) # When no pick is passed, the __str__ result is printed >>> f"{c}" 'A RGB color' # When `obj!r` is used, the __repr__ output is printed >>> f"{c!r}" 'Color(r=123, grand=32, b=255)' # Same every bit the default >>> f"{c!s}" 'A RGB colour'
Python likewise allows us to control the formatting on a per-type basis through the __format__
method. The following case shows how you lot tin can do all of that.
>>> course Color: def __init__(cocky, r: float = 255, g: bladder = 255, b: bladder = 255 ): self.r = r self.g = chiliad cocky.b = b def __str__(self) -> str: return "A RGB color" def __repr__(self) -> str: return f"Color(r={cocky.r}, g={self.g}, b={cocky.b})" def __format__(self, format_spec: str) -> str: if non format_spec or format_spec == "southward": return str(self) if format_spec == "r": render repr(self) if format_spec == "five": return f"Color(r={self.r}, g={cocky.g}, b={self.b}) - A nice RGB thing." if format_spec == "vv": return ( f"Color(r={self.r}, one thousand={self.yard}, b={self.b}) " f"- A more verbose nice RGB thing." ) if format_spec == "vvv": return ( f"Color(r={cocky.r}, m={self.g}, b={self.b}) " f"- A SUPER verbose squeamish RGB matter." ) raise ValueError( f"Unknown format code '{format_spec}' " "for object of blazon 'Colour'" ) >>> c = Colour(r=123, m=32, b=255) >>> f'{c:v}' 'Colour(r=123, g=32, b=255) - A squeamish RGB matter.' >>> f'{c:vv}' 'Color(r=123, thou=32, b=255) - A more than verbose nice RGB affair.' >>> f'{c:vvv}' 'Color(r=123, g=32, b=255) - A SUPER verbose nice RGB matter.' >>> f'{c}' 'A RGB color' >>> f'{c:s}' 'A RGB color' >>> f'{c:r}' 'Color(r=123, k=32, b=255)' >>> f'{c:j}' --------------------------------------------------------------------------- ValueError Traceback (most recent phone call concluding) <ipython-input-20 -anec0ee8dd74be> in <module> ----> 1 f'{c:j}' <ipython-input-15 -985c4992e957> in __format__(self, format_spec) 29 f"- A SUPER verbose nice RGB thing." 30 ) ---> 31 raise ValueError( 32 f"Unknown format code '{format_spec}' " "for object of type 'Color'" 33 ) ValueError: Unknown format code 'j' for object of type 'Color'
Lastly, in that location'due south too the a
choice that escapes non-ASCII chars. For more info: docs.python.org/iii/library/functions.html#as..
>>> utf_str = "Áeiöu" >>> f"{utf_str!a}" "'\\xc1ei\\xf6u'"
How to Use F-Strings to Format a Float
f-strings allow format float numbers similar to str.format
method. To do that, you lot can add a :
(colon) followed past a .
(dot) and the number of decimal places with a f
suffix.
For example, y'all tin can round a float to 2 decimal places and print the variable just like this:
>>> num = 4.123956 >>> f"num rounded to 2 decimal places = {num:.2f}" 'num rounded to 2 decimal places = four.12'
If you don't specify anything, the bladder variable will use the full precision.
>>> print(f'{num}') 4.123956
How to Format a Number as Percentage
Python f-strings have a very convenient way of formatting percentage. The rules are similar to float formatting, except that y'all suspend a %
instead of f
. Information technology multiplies the number past 100 displaying information technology in a fixed format, followed by a percent sign. You can also specify the precision.
>>> total = 87 >>> true_pos = 34 >>> perc = true_pos / full >>> perc 0.39080459770114945 >>> f"Percent of true positive: {perc:%}" 'Percentage of true positive: 39.080460%' >>> f"Percentage of true positive: {perc:.2%}" 'Per centum of true positive: 39.08%'
How to Justify or Add Padding to a F-Cord
You lot can justify a cord quite hands using <
or >
characters.
>>> greetings = "hello" >>> f"She says {greetings:>10}" 'She says hello' # Pad 10 char to the correct >>> f"{greetings:>x}" ' howdy' >>> f"{greetings:<10}" 'howdy ' # You tin can omit the < for left padding >>> f"{greetings:ten}" 'hullo '
>>> a = "ane" >>> b = "21" >>> c = "321" >>> d = "4321" >>> impress("\due north".join((f"{a:>x}", f"{b:>ten}", f"{c:>x}", f"{d:>x}"))) 1 21 321 4321
How to Escape Characters With f-string
In case you want to display the variable name surrounded by the curly brackets instead of rendering its value, you tin escape information technology using double {{<expr>}}
.
>>> hello = "world" >>> f"{{hello}} = {hi}" '{hello} = world'
Now, if you want to escape a double quote, you can use the backslash \"
.
>>> f"{how-do-you-do} = \"hello\"" 'earth = "hello"'
How to Center a String
Centering a string can exist achieved by using var:^N
where var
is a variable yous want to brandish and N
is the string length. If Northward
is shorter than the var
, and then Python display the whole string.
>>> hullo = "globe" >>> f"{hullo:^11}" ' globe ' >>> f"{hello:*^11}" '***earth***' # Extra padding is added to the right >>> f"{hi:*^10}" '**world***' # N shorter than len(hello) >>> f"{hullo:^2}" 'world'
How To Add together a Chiliad Separator
f-strings too allow us to customize numbers. One common performance is to add an underscore to separate every thousand identify.
>>> big_num = 1234567890 >>> f"{big_num:_}" '1_234_567_890'
How to Format a Number With Commas as Decimal Separator
In fact, you tin can use any char as separator. It's besides possible to employ a comma equally separator.
>>> big_num = 1234567890 >>> f"{big_num:,}" 'i,234,567,890'
You can besides format a float with commas and set the precision in i go.
>>> num = 2343552.6516251625 >>> f"{num:,.iiif}" '2,343,552.652'
How to Format a Number With Spaces as Decimal Separator
What about using spaces instead?
Well, this i is a scrap "hacky" only it works. Y'all can utilise the ,
as separator, then replace information technology with space.
>>> big_num = 1234567890 >>> f"{big_num:,}".replace(',', ' ') 'one 234 567 890'
Another option is to set the locale of your environment to one that uses spaces as a thousand separator such as pl_PL
. For more than info, see this thread on stack overflow.
How to Format a Number in Scientific Annotation (Exponential Annotation)
Formatting a number in scientific notation is possible with the eastward
or Eastward
pick.
>>> num = 2343552.6516251625 >>> f"{num:e}" '2.343553e+06' >>> f"{num:E}" 'two.343553E+06' >>> f"{num:.iidue east}" '2.34e+06' >>> f"{num:.4East}" '2.3436E+06'
Using if-else
Provisional in a F-Cord
f-strings besides evaluates more than circuitous expressions such as inline if/else
.
>>> a = "this is a" >>> b = "this is b" >>> f"{a if x > five else b}" 'this is a' >>> f"{a if 10 < 5 else b}" 'this is b'
How to Use F-String With a Dictionary
You can use dictionaries in a f-cord. The only requirement is to use a different quotation mark than the one enclosing the expression.
>>> color = {"R": 123, "G": 145, "B": 255} >>> f"{color['R']}" '123' >>> f'{colour["R"]}' '' 123 ' >>> f"RGB = ({color['R']}, {color['G']}, {color['B']})" 'RGB = (123, 145, 255)'
How to Concatenate F-Strings
Concatenating f-strings is similar concatenating regular strings, you can practise that implicitly, or explicitly by applying the +
operator or using str.join
method.
# Implicit cord concatenation >>> f"{123}" " = " f"{100}" " + " f"{20}" " + " f"{3}" '123 = 100 + 20 + 3' # Explicity concatenation using '+' operator >>> f"{12}" + " != " + f"{13}" '12 != xiii' # string concatenation using `str.join` >>> " ".join((f"{13}", f"{45}")) '13 45' >>> "#".bring together((f"{13}", f"{45}")) 'xiii#45'
How to Format a Date With F-String
f-strings likewise back up the formatting of datetime
objects. The process is very similar to how str.format
formats dates. For more than info well-nigh the supported formats, check this table in the official docs.
>>> import datetime >>> now = datetime.datetime.now() >>> ten_days_ago = at present - datetime.timedelta(days=10) >>> f'{ten_days_ago:%Y-%m-%d %H:%1000:%S}' '2020-10-xiii 20:24:17' >>> f'{now:%Y-%m-%d %H:%M:%S}' '2020-10-23 20:24:17'
How to Add Leading Zeros
You tin can add leading zeros past adding using the format {expr:0len}
where len
is the length of the returned cord. You lot can include a sign option. In this instance, +
means the sign should exist used for positive and negative numbers. The -
is used but for negative numbers, which is the default behavior. For more info, check the string format specification folio .
>>> num = 42 >>> f"{num:05}" '00042' >>> f'{num:+010}' '+000000042' >>> f'{num:-010}' '0000000042' >>> f"{num:010}" '0000000042' >>> num = -42 >>> f'{num:+010}' '-000000042' >>> f'{num:010}' '-000000042' >>> f'{num:-010}' '-000000042'
Conclusion
That's it for today, folks! I hope you've learned something different and useful. Knowing how to brand the most out of f-string can make our lives so much easier. In this post, I showed the nearly common tricks I employ in a day-to-day ground.
Other posts you may similar:
- How to Check if an Exception Is Raised (or Not) With pytest
- Everything You lot Need to Know About Python's Namedtuples
- The Best Way to Compare Two Dictionaries in Python
- eleven Useful Resources To Learn Python's Internals From Scratch
- seven pytest Features and Plugins That Will Save Y'all Tons of Time
See you next time!
Source: https://miguendes.me/73-examples-to-help-you-master-pythons-f-strings
0 Response to "Read in Paragraph as One Element Python"
Post a Comment