There are various ways to concatenate int and string.
Approach 1: Converting int to string
str() function is used to convert int to string.
Example
msg = 'My age is ';
age = 32
str1 = msg + str(age)
Approach 2: Using % operator.
str2 = "%s%s" % (msg, age)
Approach 3: Using format function.
str3 = "{}{}".format(msg, age)
Approach 4: Using f-strings.
str4 = f'{msg}{age}'
Find the below working application.
string_int_concate.py
msg = 'My age is ';
age = 32
str1 = msg + str(age)
print(str1)
str2 = "%s%s" % (msg, age)
print(str2)
str3 = "{}{}".format(msg, age)
print(str3)
str4 = f'{msg}{age}'
print(str4)
Output
$python3 main.py
My age is 32
My age is 32
My age is 32
My age is 32
No comments:
Post a Comment