Formatting a String
The most important part of a code is the input, logic, and output. All three parts require some sort of formatting while writing the code for better and easy-to-read outputs. Well, python offers a variety of methods to format a string.
Python: 3.0    Abhay Parashar    04 Jul 2021   0
Login to upvote
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
name = "Abhay"
age = 21

## METHOD 1: Concatenation
print("My name is "+name+", and I am "+str(age)+ " years old.")

## METHOD 2: F-strings (Python 3+)
print(f"My name is {name}, and I am {age} years old")

## METHOD 3: Join
print(''.join(["My name is ", name, ", and I am ", str(age), " years old"]))

## METHOD 4: modulus operator
print("My name is %s, and I am %d years old." % (name, age))

## METHOD 5: format(Python 2 and 3)
print("My name is {}, and I am {} years old".format(name, age))
Copy | Download as: .py file   PNG
Share on: FB   Twitter   LinkedIn   WA
©2021 - code108labs   Contributors   Hosted on DigitalOcean   Partner website: pythoncircle.com