Skip to content

Latest commit

 

History

History
86 lines (65 loc) · 1.55 KB

notes.md

File metadata and controls

86 lines (65 loc) · 1.55 KB

Day 28 - f-String

Python 3.6 onwards f-strings are introduced. They allow us to place the variables inside strings more conveniently. This is used to format strings.

Conventional way of writing strings with variables

Method 1 : using + operator
name = 'Sarang'
country = 'India'
string = 'Hey! I am '+ name +' and I am from '+country+'.'
print(string)

Output

Hey! I am Sarang and I am from India.
Method 2 : using tuple join method
name = 'Sarang'
country = 'India'
string = 'Hey! I am', name,'and I am from',country,'.'
# as string is now tuple - we need to convert it to string
string = ' '.join(string)
print(string)

Output

Hey! I am Sarang and I am from India.
Method 3 : using list join method
name = 'Sarang'
country = 'India'
string = ['Hey! I am', name,'and I am from',country,'.']
string = ' '.join(string)
print(string)

Output

Hey! I am Sarang and I am from India.
Method 4 : Using string method
name = 'Sarang'
country = 'India'
string = 'Hey! I am {} and I am from {}'.format(name, country)
print(string)

Output

Hey! I am Sarang and I am from India.
Method 5 : Using f-string
name = 'Sarang'
country = 'India'
string = f'Hey! I am {name} and I am from {country}'
print(string)

Output

Hey! I am Sarang and I am from India.

Click here for more examples on f-strings


References