放置在单独行上的Python连接字符串语句

2024-09-29 17:16:02 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我尝试过的结果,但出现了错误:

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

请让我知道,当字符串值放在单独的行上时,如何将它们赋给变量。你知道吗


Tags: pygetif错误lineelsefile空格
2条回答

最简单的解决方案是将行包装在parethesis中,以表明它们属于一起:

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" 

或者,如果语句带有括号,则不需要\作为:

result = ("a" + 
          "b" + 
          "c")

相关问题 更多 >

    热门问题