python - 在多行中连接python中的字符串

标签 python string concatenation

我有一些要连接的字符串,结果字符串会很长。我还有一些变量要连接。

如何将字符串和变量结合起来,使结果成为多行字符串?

以下代码抛出错误。

str = "This is a line" +
       str1 +
       "This is line 2" +
       str2 +
       "This is line 3" ;

我也试过了

str = "This is a line" \
      str1 \
      "This is line 2" \
      str2 \
      "This is line 3" ;

请提出一种方法来做到这一点。

最佳答案

有几种方法。一个简单的解决方案是添加括号:

strz = ("This is a line" +
       str1 +
       "This is line 2" +
       str2 +
       "This is line 3")

如果您希望每个“行”在单独的行上,您可以添加换行符:

strz = ("This is a line\n" +
       str1 + "\n" +
       "This is line 2\n" +
       str2 + "\n" +
       "This is line 3\n")

关于python - 在多行中连接python中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34295901/

相关文章:

python - 如何将字符串转换为整数并将它们相加?

r - 遍历列表 R

c++ - 字符串与整数的连接

python - 共享 Python virtualenv 环境

python - 使用python读取文件并创建多维字典

java - 将 HashSet<String> 与 String.equals(...) 进行比较

javascript - 用 JavaScript 中的范围替换字符串中的子字符串

python - TensorFlow 1.7 + Keras 和数据集 : Object has no attribute 'ndim'

python - 在 Mac 上安装 pylinkgrammar

c++ - 在不使用循环的情况下,将 ISBN-10 的前 9 位数字作为字符串读取并计算第 10 位数字