String Formatting in Python
How To Format Strings in Python #PySeries#Episode 35
Hi, this is a quick note about strings in python.
Let’s get it on?
String Interpolation → Injects a variable into your string printing
2 methods:
. format()
. f-strings
format() method:
print('This is a string {}'.format('INSERTED'))This is a string INSERTED
Multiples strings — when order matters!
print('{} {} {}.'.format('brown', 'quick', 'fox') )brown quick fox.
Positional arguments:
print('{1} {0} {2}.'.format('brown', 'quick', 'fox') )quick brown fox.
Or keywords arguments:
print('{q} {b} {f}'. format(b = 'brown', q = 'quick', f = 'fox'))quick brown fox
Float formatting follows “{value: width.precision f}”
result = 100/777
Printing directly:
print("The result was {}".format(result))The result was 0.1287001287001287
Or formatting the number:
print("The result was {r:1.3f}".format(r = result))The result was 0.129
Width (creates space for the number):
print("The result was {r:10.3f}".format(r = result))The result was 0.129
f-strings Mehod
name = 'j3'print('His name is {}'.format(name))His name is j3
New for Python 3.6 → f-strings literals:
print(f'His name is {name}')His name is j3
And finally:
print("That's is all for now, folks o/ {}".format("Thank you!"))That's is all for now, folks o/ Thank you!
👉Colab notebook link :)
Credits & References
Jose Portilla —2021 Complete Python Bootcamp From Zero to Hero in Python— Learn Python like a Professional Start from the basics and go all the way to creating your own applications and games.
Awesome Source: https://pyformat.info/
Posts Related:
00Episode#PySeries — Python — Jupiter Notebook Quick Start with VSCode — How to Set your Win10 Environment to use Jupiter Notebook