In Python, f-string is used a lot to format output strings for various development purposes, but you know what else is really cool? I’ll give you a list today. The source address
Output variable names directly to make your code simpler, syntax based on Python3.10
string = 'Hello Medusa'
print(f'{string = }')
Copy the code
string = 'Hello Medusa'
Copy the code
The results are evaluated directly to alter the output, with syntax based on Python3.10
number = 1024
print(f'{number % 1 =}')
Copy the code
number % 1 =0
Copy the code
Event objects are formatted for output directly, with syntax based on Python3.10
datetime = datetime.datetime.now()
print(f'{datetime:%Y-%m-%d %H:%M:%S}')
Copy the code
The 2021-12-26 16:03:20Copy the code
Base conversion output, syntax based on Python3.10
number_10 = 1024
print(f'{number_10:b}') # 2 into the system
print(f'{number_10:o}') # 8 hexadecimal
print(f'{number_10:x}') Hexadecimal lowercase
print(f'{number_10:X}') # hex uppercase
print(f'{number_10:c}') # ASCII encoding
Copy the code
10000000000 2000 400 400Copy the code
Format floating point numbers with syntax based on Python3.10
number_float = 1024.123
print(f'{number_float = :2.f}') Keep two decimal places
number_float_format = '.3f'
print(f'{number_float:{number_float_format}} ') The parameter is nested, and the decimal point is reserved for three decimal places
Copy the code
Number_float = 1024.12 1024.123Copy the code
For strings, the syntax is based on Python3.10
text = 'Medusa'
print(f'{text:>10}') # right-aligned
print(f'{text:<10}') # left-aligned
print(f'{text:^10}') # center align
print(f'{text:*^10}') Use * to fill in the blanks
n = 10
print(f'{text:~^{n}} ') # parameter nested, center aligned, fill blank with ~
Copy the code
Medusa
Medusa
Medusa
**Medusa**
~~Medusa~~
Copy the code
! S and! R, the syntax is based on Python3.10
text = 'Medusa'
print(f'{text! s}') # str(text)
print(f'{text! r}') # repr(text)
Copy the code
Medusa
'Medusa'
Copy the code
Custom format, syntax is based on Python3.10
class MedusaFormatString:
def __format__(self, format_spec) :
return format_spec
print(f'{MedusaFormatString():&1&2}')
Copy the code
& 1 & 2Copy the code
Live hard!