Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # Author: Nageswara Rao
- # F-strings are introduced in python 3.6. To use f-strings your python version should be >=3.6
- # Simple example using format()
- >>> name = 'Nageswara Rao'
- >>> language = 'Python'
- >>> old_style = 'Hai, I am {} and I am working on {}'.format(name, language)
- >>> print(old_style)
- Hai, I am Nageswara Rao and I am working on Python
- # Using f string - Simple example
- >>> name = 'Nageswara Rao'
- >>> language = 'Python'
- >>> with_f_string = f'Hai, I am {name} and I am working on {language}'
- >>> print(with_format)
- Hai, I am Nageswara Rao and I am working on Python
- # We can do calculations also
- >>> text = f'3 times 9 is equals to {3 * 9}'
- >>> print(text)
- 3 times 9 is equals to 27
- # Padding made easy - With out padding
- >>> for n in range(0, 4):
- ... text = f'The value is {n}'
- ... print(text)
- ...
- The value is 0
- The value is 1
- The value is 2
- The value is 3
- # With padding - Leading 0 for single digits
- >>> for n in range(0, 12):
- ... text = f'The value is {n:02}'
- ... print(text)
- ...
- The value is 00
- The value is 01
- The value is 02
- The value is 03
- The value is 04
- The value is 05
- The value is 06
- The value is 07
- The value is 08
- The value is 09
- The value is 10
- The value is 11
- # Format longer floating poing
- >>> from math import pi
- >>> formatted_pi = f'Pi equals to {pi:.4f}'
- >>> print(formatted_pi)
- Pi equals to 3.1416 # See value formatted and also rounded off
- >>> formatted_pi = f'Pi equals to {pi:.5f}'
- >>> print(formatted_pi)
- Pi equals to 3.14159
- # Formatting date - How simple it is
- >>> from datetime import datetime
- >>> birthday = datetime(1992, 3, 5)
- >>> format_birthday = f'Narendra has a birthday on {birthday:%B %d, %Y}'
- >>> print(format_birthday)
- Narendra has a birthday on January 03, 1990
- # f-strings parsing is smart enough to handle named unicode code points
- >>> ordinal, unicode = "Hello", "I'm an software engineer"
- >>> print(f'{ordinal}, {unicode}')
- Hello, I'm an software engineer
Add Comment
Please, Sign In to add comment