Wednesday, June 22, 2022

Python - Formatting strings

# A simple approach
myVar = "caveman"
txt = "So easy a " + myVar + " could do it"
print(txt)

# Fancy
age = 36
txt = "My name is John, and I am not {}"
print(txt.format(age))

# Fancier
age = 36
name = "John"
txt = "My name is {}, and I am not {}"
print(txt.format(name, age))

# Fancy-pants
# Notice the order
quantity = 3
itemno = 567
price = 49.95
myOrder = "I want to pay {2} dollars for {0} pieces of item {1}."
# This will print "I want to pay 49.95 dollars for 3 pieces of item 567."
print(myOrder.format(quantity, itemno, price))

print ("---")

# The following line of code will never work
# Because of the quotes around the word "never"
#txt = "This will "never" work"

# The fix is to escape the quotes
txt = "This will \"never\" work"

print(txt)