String Concatenation in Python

In Python, you can combine two or more alphanumeric strings using the + operator.

string1 + string2

When dealing with alphanumeric data, the Python interpreter concatenates the two strings (whether they are variables or constants).

However, if the operands are numeric, the Python interpreter uses the plus sign to add the two values together.

Note: If the operands are of different data types, such as a string and a number (e.g., "3" + 4), the Python interpreter will raise an error. To prevent this, you should handle exceptions in your code or convert both pieces of data to strings (str) before concatenation.

Practical Example

In the following example, I assign three alphanumeric values to three variables.

Then, I concatenate them into the variable `name`.

string1="Andrea"
string2=" "
string3="Minini"
name=string1+string2+string3
print(name)

The program output will be:

Andrea Minini

String concatenation works with both constants and variables.

In this example, I rewrite the program using two variables and a space as a constant " ".

string1="Andrea"
string3="Minini"
name=string1+" "+string3
print(name)

The final result is the same:

Andrea Minini

String concatenation in Python is really straightforward.

Repeating a String Multiple Times

To repeat the same alphanumeric string multiple times, you can use the * operator.

string*5

Example 1

In the following code, I assign the string "hello" to the variable `string`.

Then, I multiply it by 5 and display the result.

string="hello"
print(string*5)

The output will be:

hellohellohellohellohello

This demonstrates string repetition.

Example 2

You can also repeat an alphanumeric constant, not just a variable.

string="hello"*5
print(string)

The final result is the same:

hellohellohellohellohello

And that’s it!

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Strings in Python

FAQ