Quantcast
Channel: JS Tricks » Python
Viewing all articles
Browse latest Browse all 25

Python string concatenation tutorial

$
0
0

Concatenation is the process to combine multiple strings into a new string. In this lesson we will learn about Python string concatenation.

Python string concatenation

Python string concatenation

Python string concatenation

In Python you can concatenate strings by using + operator. But remember that each and every part must be string. You cannot concatenate a string and a number ( integer ). So make sure that your have converted all of your variables to string before concatenating. You can use str function to convert any type of variable to string.

Here are some examples of Python string concatenation:

string1 = "My name is : "
string2 = "John Doe"
print string1 + string2

The output will be like this:

My name is : John Doe

Now lets try for a concatenation for a string and an integer.

mystring = "My age is : "
myinteger = 27
print mystring + myinteger

Now it will show an error like this:

TypeError: cannot concatenate 'str' and 'int' objects

To concatenate different types of variable you should change all of the types to string. So you can concatenate these two variables (a string and an integer) by converting the type of integer to string. Here is the solution for you:

mystring = "My age is : "
myinteger = 27
print mystring + str( myinteger )

And you will get the expected output:

My age is : 27

Hope now you know about Python string concatenation. Enjoy Python.

The post Python string concatenation tutorial appeared first on JS Tricks.


Viewing all articles
Browse latest Browse all 25

Trending Articles