filmov
tv
Python f-String Formatting with Examples - Learn Python Programming - APPFICIAL
Показать описание
As of Python 3.6+, f-strings have become the most popular way to format strings. Not only are they more readable, more concise, and less prone to error than other ways of formatting (such as %-formatting), are are also faster! F-string stands for formatted string literal, and it works by creating placeholder expressions that are evaluated as the program executes. The typical format is you start with f’ then you add your string with {variable} inside the string wherever you need a variable value to be.
Ex: name = ’Bob’
age = 65
print(f’{name} is {age} years old’)
There are some cool things you can do with f-strings, such as adding an = sign at the end of a math expression, to also print out the result.
Ex: print(f’{2*3=}’) prints the string "2*3=6".
You can also provide some format specifications or presentation types when using f-strings to customize the formatting of the string.
Ex:
price = 12.423343
print(f’The price is ${price:.2f}’)
The .2 means only display 2 numbers after the decimal, and the f mean fixed-point notation. Other types are:
s – string (optional)
d – decimal (integer values)
b – binary
x – hexadecimal in lowercase (integer values)
X – hexadecimal in uppercase (integer values)
e – exponential notation
f – fixed-point (6 decimal places by default)
.[precision]f – fixed-point notation (programmer defined)
0[precision]d – leading 0 notation
Subscribe to Appficial for more programming videos coming soon. Also, don't forget to click LIKE and comment on the video if it helped you out!
Ex: name = ’Bob’
age = 65
print(f’{name} is {age} years old’)
There are some cool things you can do with f-strings, such as adding an = sign at the end of a math expression, to also print out the result.
Ex: print(f’{2*3=}’) prints the string "2*3=6".
You can also provide some format specifications or presentation types when using f-strings to customize the formatting of the string.
Ex:
price = 12.423343
print(f’The price is ${price:.2f}’)
The .2 means only display 2 numbers after the decimal, and the f mean fixed-point notation. Other types are:
s – string (optional)
d – decimal (integer values)
b – binary
x – hexadecimal in lowercase (integer values)
X – hexadecimal in uppercase (integer values)
e – exponential notation
f – fixed-point (6 decimal places by default)
.[precision]f – fixed-point notation (programmer defined)
0[precision]d – leading 0 notation
Subscribe to Appficial for more programming videos coming soon. Also, don't forget to click LIKE and comment on the video if it helped you out!
Комментарии