We provide affordable online training course for Python and R programming at fundamental level, click here for more details.

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.

You can also watch videos on our YouTube channel for more understanding of Python programming skills.


0 Comments

Leave a Reply

Avatar placeholder