Python 连接字符串语句放在不同的行上
Python concatenating string statement placed on separate lines
这是我尝试过但出现错误的方法:
a = 1
b = 2
c = 3
d = 4
e = 5
if(1):
get = str(a) +"," #Line 1
+str(b) +"," #Line 2
+str(c) +"," #Line 3
+str(d) +"," #Line 4
+str(e) #Line 5
else:
get = ",,,,,"
print(get)
错误:
File "testingpython.py", line 8
+str(b) +"," #Line 2
^
IndentationError: unexpected indent
然后我尝试删除空格:
a = 1
b = 2
c = 3
d = 4
e = 5
if(1):
get = str(a) +"," #Line 1
+str(b) +"," #Line 2
+str(c) +"," #Line 3
+str(d) +"," #Line 4
+str(e) #Line 5
else:
get = ",,,,,"
print(get)
错误:
File "testingpython.py", line 12
else:
^
SyntaxError: invalid syntax
请告诉我如何将字符串值分配给位于不同行上的变量。
最简单的解决方案是将括号内的行换行以表明它们属于一起:
if(1):
get = ( str(a) +"," #Line 1
+str(b) +"," #Line 2
+str(c) +"," #Line 3
+str(d) +"," #Line 4
+str(e) #Line 5
)
else:
get = ",,,,,"
print(get)
但您可以使用更短的方法:
get = ','.join(str(s) for s in [a, b, c, d, e])
在Python中我们通常使用\
符号将单个语句分成多行iff语句不在括号内如:
result = "a" + "b" + "c"
可以表示为:
result = "a" + \
"b" + \
"c"
或者如果语句带有括号则不需要 \
as:
result = ("a" +
"b" +
"c")
这是我尝试过但出现错误的方法:
a = 1
b = 2
c = 3
d = 4
e = 5
if(1):
get = str(a) +"," #Line 1
+str(b) +"," #Line 2
+str(c) +"," #Line 3
+str(d) +"," #Line 4
+str(e) #Line 5
else:
get = ",,,,,"
print(get)
错误:
File "testingpython.py", line 8
+str(b) +"," #Line 2
^
IndentationError: unexpected indent
然后我尝试删除空格:
a = 1
b = 2
c = 3
d = 4
e = 5
if(1):
get = str(a) +"," #Line 1
+str(b) +"," #Line 2
+str(c) +"," #Line 3
+str(d) +"," #Line 4
+str(e) #Line 5
else:
get = ",,,,,"
print(get)
错误:
File "testingpython.py", line 12
else:
^
SyntaxError: invalid syntax
请告诉我如何将字符串值分配给位于不同行上的变量。
最简单的解决方案是将括号内的行换行以表明它们属于一起:
if(1):
get = ( str(a) +"," #Line 1
+str(b) +"," #Line 2
+str(c) +"," #Line 3
+str(d) +"," #Line 4
+str(e) #Line 5
)
else:
get = ",,,,,"
print(get)
但您可以使用更短的方法:
get = ','.join(str(s) for s in [a, b, c, d, e])
在Python中我们通常使用\
符号将单个语句分成多行iff语句不在括号内如:
result = "a" + "b" + "c"
可以表示为:
result = "a" + \
"b" + \
"c"
或者如果语句带有括号则不需要 \
as:
result = ("a" +
"b" +
"c")