Many ways of formatting strings in Python

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

There are so many ways of formatting strings i Python. For example…

You can use formatted string…

location = "New York"
temperature = 76.22
greeting = f"Temperature in {location} is {temperature}"
# Temperature in New York is 76.22

Or you can use the format method of a string with placeholders that are index or name based. The following gives the same results…

greeting = "Temperature in {} is {}".format(location, temperature)
greeting = "Temperature in {0} is {1}".format(location, temperature)
greeting = "Temperature in {1} is {0}".format(temperature, location)
greeting = "Temperature in {location} is {temperature}".format(location="New York", temperature="76.22")

You can place formatting information in the placeholder. The following will display the temperature in one decimal place…

greeting = "Temperature in {} is {:.1f}".format(location, temperature)

The following gives a field of 10 character padded with leading zeros…

greeting = "Temperature in {} is {:0>10.1f}".format(location, temperature)

The older string formatter does similarly…

greeting = "Temperature in %s is %.1f" % (location, temperature)

With named place holders, you can define a formatter function like this …

greeting_formatter = "Temperature in {location} is {temperature}".format

print(greeting_formatter(location="Dallas", temperature="82.6"))

If you need to display literal braces in the string, double it up…

greeting = "{{Hi}}: Temperature in {} is {}".format(location, temperature)
# {Hi}: Temperature in New York is 76.22

Similarly if you need a % in your string in the older style format…

greeting = "Temperature%% in %s is %.1f" % (location, temperature)
# Temperature% in New York is 76.2

If you have a dictionary, your placeholder can extract values from it like this…

weather = {"location":  "New York", "temperature": 76.22}
greeting = "Temperature in {0[location]} is {0[temperature]}".format(weather)

Or if you have a list, you can do similarly…

weather = ["New York", 76.22 ]
greeting = "Temperature in {0[0]} is {0[1]}".format(weather)

Related Posts

Tags

Share This