1

These work for creating a string by defining it's individual elements separately:

str1 = ("a" "b")
# str1 = 'ab'

str2 = ("d"+str1)
# str2 = 'dab'

str3 = ("d" "e" "f")
# str3 = 'def'

But this one fails. Why so?

str3 = ("d"+str1 "e")
# SyntaxError: invalid syntax

What's the work around it?

Vishal
  • 3,178
  • 2
  • 34
  • 47

2 Answers2

6

You're mixing two different things. ("a" "b") looks like it's two strings, but it's really only one; string literals separated by whitespace are automatically concatenated to a single string. It's identical to using ("ab").

On the other hand, you can add two different strings to make a new single string. That's what's happening with ("d"+str1).

The trick in the first example only works with string literals, not with variables or more complicated expressions. So ("d"+str1 "e") doesn't work. You need ("d"+str1+"e"), which is two additions.

P.S. the parentheses are optional, they just group together operations that don't need any additional grouping.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
3

Two string literals next to each other are automatically concatenated; this only works with two literals, not with arbitrary string expressions:

>>> 'str' 'ing'                   #  <-  This is ok
'string'
>>> 'str'.strip() + 'ing'   #  <-  This is ok
'string'
>>> 'str'.strip() 'ing'     #  <-  This is invalid
  File "<stdin>", line 1, in ?
    'str'.strip() 'ing'
                      ^
SyntaxError: invalid syntax

The Python Tutorial

More clearer: enter image description here

宏杰李
  • 11,820
  • 2
  • 28
  • 35
  • This is a very vague answer! Also, incorrect. This way of creating strings can work with more than 3 string elements. – Vishal Jan 07 '17 at 03:22
  • @vishal This is from The Python Tutorial, if you do not satisfy with it, propose a PEP may be a better choice. – 宏杰李 Jan 07 '17 at 03:25
  • @vishal I think the emphasis is on the fact that both have to be string literals (it can't just be 1 of them is). 3 string literals is actually 2 string literals side-by-side twice. – 4castle Jan 07 '17 at 03:42