5.3. Formatting Strings#
Dynamic strings
name='Sahil'
age=25
5.3.1. Using .format()#
print('My name is {}. I am {} years old'.format(name,age))
My name is Sahil. I am 25 years old
5.3.2. F-string - Better way !!#
Just place f in start of string
You can add variables directly
You don’t need to first convert everything to string and then do concatenation
print(f"My name is {name}. I am {age} years old")
My name is Sahil. I am 25 years old
You can run functions on variables and evaluate or perform computation within string
print(f"My name is {name.upper()}. I am {float(age+1)} years old")
My name is SAHIL. I am 26.0 years old
dict={'name':'sahil','age':25}
print(f'My name is {dict['name']}. I am {dict['age']} years old')
Input In [6]
print(f'My name is {dict['name']}. I am {dict['age']} years old')
^
SyntaxError: f-string: unmatched '['
Note: Error came because pythn gets confused in single quotes used in string
So,always use double quotes to start and end a string
print(f"My name is {dict['name']}. I am {dict['age']} years old")
My name is sahil. I am 25 years old