String Formatting for Printing with Python
I am going to walk-through a few examples of String Formatting for Print with Python. I went through Python Dev Bootcamp a while back and took notes that I refer many times over. I thought I should share a series of them, and also as a reference for me in the future.
The below examples use .format() and f string methods for printing in python.
String Formatting for Printing
- Basic Printing
- Ex 1:
- print(“Hello”)
- Prints “Hello”
- I have been using Anaconda Navigator for testing out Python. I would highly recommend it as it visualizes your work
- Showing Length of the String
- len(“Hello World”)
- Output: 11
- Ex 1:
- .format()
- “String here {} then also {}”.format(“Tex”,”Nothing”)
- You can also change the order of the strings by having the order of priority in curly braces
- print(“I have a {2} {0} {1}”.format(“black”,”labrador”,”dog”))
- It will print: I have a dog black labrador
- I can also repeat terms multiple times
- print(“I have a {0} {0} {1}”.format(“black”,”labrador”,”dog”))
- I have a black black labrador
- You can also use keyword phrases to insert text
- print(“I have a {color} {breed} {animal}”.format(color=”black”,breed=”labrador”,animal=”dog”))
- Printing a variable
- result = 100/777
- “He got a result of {}”.format(result)
- ‘He got a result of 0.1287001287001287’
- Alternatively:
- “He got a result of {r}”.format(r=result)
- ‘He got a result of 0.1287001287001287’
- F String to insert text
- name = “Jose”
- age = 10
- print(f”His name is {name}, and his age is {age}”)
Future Python Development Notes
I have previously talked about Learning to Code in Python, where I talked about me picking up python and using it for my side projects. I mostly learned Python through Udemy courses and Youtube. One of the key items that I need to spend more time on is Object Oriented Programming.
I think I will start posting more of my Python notes and since I am relatively a beginner, I am hoping others who are starting out can find it useful. There are already a tonne of great Python beginner content out there, but I will be capturing my journey as I progress through my Python development skills. If you folks have any other feedback, I am more than happy to hear.