Tags
Asked 3 years ago
2 Aug 2021
Views 610
steave ray

steave ray posted

TypeError: can only concatenate str (not

i am trying to concat two or more than string and integer value in print() function

a=1
print("hello world "+(str)a+" go to world")

i got following error for above code
TypeError: can only concatenate str (not "int") to str

so it tried to cast integer to string

a=1
print("hello world "+(str)a+" go to world")

and for above code for using (str) as to type cast and get error is:
[]bSyntaxError: invalid syntax[/b]

a=1
print("hello world "+(string)a+" go to world")

and for above code for using (string) as to type cast and get error is:
[]bSyntaxError: invalid syntax[/b]

so how to type cast integer to string with print() function in python?
ravi

ravi
answered Aug 2 '21 00:00

for float to string cast convert with print() function :

a=1.3
print("hello world "+str(a)+" go to world")
print("hello world {0} go to world".format(a))

you can use either str() or fomat()
sec8

sec8
answered Aug 2 '21 00:00


a=1
print("hello world {0} go to world".format(1))

use format() function to convert integer to string .
david

david
answered Aug 3 '21 00:00

or you can Formatted String Literals like this for the above examples :

integer to string with Formatted String Literals in print function

a=1
print(f'integer to string is {a} ')


result:

integer to string is 1 


float to string with Formatted String Literals in print function

a=1.34
print(f'float to string is {a:.3f} ')


result :

float to string is 1.340 


or print pi value with five floating precision

import math
print(f'The value of pi is approximately {math.pi:.5f}.')


result :

The value of pi is approximately 3.14159.


you can notice f before string start at print() function is shorthand for formatting function.
ching

ching
answered Aug 4 '21 00:00

try this also :

a=1.56
print("hello world ",a," go to world")


result:

hello world  1.56  go to world


so easy
jignesh

jignesh
answered Aug 2 '21 00:00

try str() function to do type cast from integer to string in python

a=1
print("hello world "+str(a)+" go to world")
Post Answer