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