Why ‘1’+’2′ = ’12’ in Python

python what is the result of '1'+'2'

In Python, ‘1’ + ‘2’ is equal to ’12’.

This is because both ‘1’ and ‘2’ are strings so the + operation adds one string to the end of the other. This is called string concatenation.

If you used integers instead, the result would be 3.

What Is String Concatenation in Python

String concatenation in Python means adding two or more strings together. In this process, one string is added to the end of the other.

To concatenate two or more strings, call the + operator on the strings.

For instance:

s1 = "Hello "
s2 = "World"

words = s1 + s2

print(words)

Output:

Hello World

The same applies when applying string concatenation to strings that represent numeric values.

For example:

s1 = '1'
s2 = '2'

both = s1 + s2

print(both)

Output:

12

Now that you understand how string concatenation works, let’s take a look at a common issue beginners usually face.

Why Is 1+2=12 When It Should be 3?

If you have a program that asks a user for two numbers to sum them up, you may bump into a strange issue:

number1 = input("Enter a number: ")
number2 = input("Enter another numnber: ")

result = number1 + number2

print(f"The result is {result}")

Example run:

Enter a number: 1
Enter another numnber: 2
The result is 12

The result is obviously supposed to be 3, but it is 12. So what is the matter here?

This is because the user inputs are strings by default—not numbers as you may assume.

To solve this little problem, convert the strings into numbers.

If you want the user to input integers, you can convert the strings to integers using the built-in int() function.

Here is how to do it:

number1 = int(input("Enter a number: "))
number2 = int(input("Enter another numnber: "))

result = number1 + number2

print(f"The result is {result}")

Now the program works as expected.

Enter a number: 1
Enter another numnber: 2
The result is 3

Conclusion

Today you learned what Python string concatenation means why the result of ‘1’+’2′ is equal to ’12’ in Python.

To recap, string concatenation adds one string to the end of another.

When you ask for user data in your program, the data is a string by default. But you can convert it to an integer using the int() function.

Thanks for reading.

Happy coding!

Further Reading

Single Quotes vs Double Quotes in Python Strings

Python Classes 101

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.