Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assigning two string objects to a variable

I understand that the below code results in SyntaxError:

x = 1 2
print(x)

But, I am not able to understand why below code is not throwing same synatax error:

x = "DataScience" "4U"
print(x)     #DataScience4U

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In Python, when you place two string literals directly adjacent to each other without any operator or separator, they are automatically concatenated into a single string. This feature is called "string concatenation."

In your second code example:

x = "DataScience" "4U"
print(x)

The two string literals "DataScience" and "4U" are placed side by side. Python treats them as a single string, concatenating them together to form "DataScience4U". The resulting string is then assigned to the variable x.

When you print the value of x, it will output the concatenated string "DataScience4U".

This behavior is specific to string literals and doesn’t apply to other types of values. In the case of the first code example where you have x = 1 2, the syntax error occurs because the Python interpreter doesn’t know how to interpret the consecutive numeric literals 1 and 2 without an operator or separator between them.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading