Last active
October 3, 2022 08:17
-
-
Save SahbiOuali13/b5242f9f7973167c7192b7a489cd7ffe to your computer and use it in GitHub Desktop.
* How to use custom string formatter in f-strings.
* Default used string formatters in f strings.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person: | |
def __init__(self, name) -> None: | |
self.name = name | |
def __format__(self, __format_spec): | |
if __format_spec == "scream": | |
return self.name.upper() + '!' | |
elif __format_spec == "repeat": | |
return self.name * 3 | |
return self.name | |
p = Person('Patrick') | |
print(f"{p}") # Patrick | |
print(f"{p:scream}") # PATRICK! | |
print(f"{p:repeat}") # PatrickPatrickPatrick | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## ROUNDING | |
>>> from math import pi | |
>>> f"The numerical value of PI is {pi}" | |
# 'The numerical value of PI is 3.141592653589793' | |
>>> f"The numerical value of PI is {pi:0.2f}" | |
# 'The numerical value of PI is 3.14' | |
## Formatting and rendering | |
name = 'Patrick' | |
>>> f"Your name is {name:_^20}" | |
'Your name is ______Patrick_______' | |
>>> f"Your name is {name:_>20}" | |
'Your name is _____________Patrick' | |
>>> f"Your name is {name:_<20}" | |
'Your name is Patrick_____________' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment