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

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

2 weeks ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

4 weeks ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

2 months ago

Document sentiment classification using bag-of-words in Python

For online Python training registration, click here ! Sentiment classification is a type of machine…

2 months ago

Download R Course source files

Click here to download R Course source files !

11 months ago

Download Python Course source files

Click here to download Python Course Source Files !

11 months ago