2

Confused with Python behavior. consider these example:

>>>a = "ww" "xx"
>>>print(a)
wwxx

>>>b = "yy" "xx"
>>>print(b)
yyxx

>>>c = a b
  File "<stdin>", line 1
    c = a b
          ^ 
SyntaxError: invalid syntax

I was expecting a result wwxxyyxx.

But got a syntax error.

Is there any difference between them(string literal and string); Both are str type.

2 Answers 2

7

Directly taken from the Python Docs Tutorial:

Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.

>>> 'Py' 'thon'
'Python'

This only works with two literals though, not with variables or expressions:

>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  ...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  ...
SyntaxError: invalid syntax

If you want to concatenate variables or a variable and a literal, use +:

>>> prefix + 'thon'
'Python'

This feature is particularly useful when you want to break long strings:

>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
Sign up to request clarification or add additional context in comments.

Comments

2

The syntax my_string = "substring1" "substring2" is a shortcut for my_string = "substring1" + "substring2" (typically when you want to split the string in multiple lines in order to make it more readable). If you do it with variables instead of constants, you're required to used the concatenation symbol.

EDIT: In your last edit, you mention the difference between string and string literal. True, they are the same data type. The difference is a question of notation. The literal is an explicit value (e.g. 2 is a notation that always represents 2) while a variable is a label that doesn't explicitly indicate its inner value (e.g. a could be 2 or 32).

In your case, "xx" will always be "xx" (literal) while during the execution of your script, your variable a could take different values (variable).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.