Archive for November, 2020

Python: Convert int to String for output

Wednesday, November 4th, 2020

I was creating a new program and wanted to generate an output string that showed the count of certain types of entries. When I attempted the simple output to get “Number of rows: 5” by using the following:

Incorrect call

rowcount = 100
print("Number of Rows: " + rowcount) 

I got the following error “TypeError: can only concatenate str (not “int”) to str” . This meant that the type of rowcount was an int but needed to be a string. There is a handy function call that takes the int and converts it to a string. The function is str() and it converts the int argument to a string value.

rowcount = 100
print("Number of Rows: " + str(rowcount))

There are other ways to output a number such as ‘%s’, format and f-string. But for my purposes. ‘str’ gave me the debugging info I needed.

Tags: