Python

Use str() to transform variable in Python

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.

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago