Python | Insert number into string



Method # 1: Using a Type Conversion
The easiest way to accomplish this is to explicitly convert an integer to a string data type using a base type conversion and append it at the appropriate position.

# Python3 code to demonstrate how it works
# Insert a number into a string
# Using type conversion

 
# initialization string

test_str = "Geeks"

 
# initialization number

test_int = 4  

  
# print original line

print ( "The original string is:" + test_str)

 
# print number

print ( "The original number:" + str (test_int))

 
# using type conversion
# Insert number into line

res = test_str + str (test_int) + test_str

 
# print result

print ( "The string after adding number is :" + str (res))

Output:

 The original string is: Geeks The original number: 4 The string after adding number is: Geeks4Geeks 

Method # 2: Using the %d operator
This operator can be used to format a string to add an integer. “D” means that the data type to insert into the string is an integer. This can be changed as required.

# Python3 code to demonstrate how it works
# Inserting a number into a string
# Using the% d operator

 
# initializing string

test_str = "Geeks"

 
# initializing number

test_int = 4  

 
# print original line

print ( "The original string is: " + test_str)

  
# print number

print ( " The original number: " + str (test_int))

 
# using the% d statement
# Insert number into line

res = (test_str + "% d " + test_str) % test_int

  
# print result

  print ( "The string after adding number is :" + str (res))

Output:

 The original string is: Geeks The original number: 4 The string after adding number is: Geeks4Geeks