In Python, if a string variable is concatenated with a numeric value directly, an error comes. In the following code example, a string variable ‘ strva’ is concatenated directly with number 2, Python returns a traceback, because these two data types can not be concatenated without transformation.
#a string variable
strva = "test string variable"
#string concatenated with number directly
strva + 2
#result
Traceback (most recent call last):
File "C:\Users\Wilso\AppData\Local\Temp\ipykernel_22144\1520423513.py", line 1, in <module>
strva + 2
To overcome this shortage, str() function can be applied to temporarily transform a numeric variable into string type before it is concatenated with a string value.
#use str() to transform numeric to string type, before concatenation
strva + str(2)
Out[4]: 'test string variable2'
This usage occurs often when user input a number and Python will use this numeric value to concatenate with other existing string together.
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…