Python format() Built Function
Python format() is a string method that allows you to format and insert values into a string. It can be used with positional arguments, keyword arguments, or both. You can also specify formatting options such as alignment, width, precision, etc.
Here are some examples of how to use Python format():
To insert values into a string using positional arguments:
txt = "My name is {0}, I'm {1}".format("John", 36)
print(txt)
Output:
My name is John, I'm 36
To insert values into a string using keyword arguments:
txt = "My name is {fname}, I'm {age}".format(fname="John", age=36)
print(txt)
Output:
My name is John, I'm 36
To insert values into a string using both positional and keyword arguments:
txt = "Hi {name}, welcome to {0} tutorials".format("Guru99", name="Jessica")
print(txt)
Output:
Hi Jessica, welcome to Guru99 tutorials
To align and pad values in a string using formatting options:
txt = "{:<10} {:>10} {:^10}".format("Apple", "Banana", "Cherry")
print(txt)
Output:
Apple Banana Cherry
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment