在多行中串联python中的字符串 [英] Concatenate strings in python in multiline

查看:38
本文介绍了在多行中串联python中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些字符串要连接,结果字符串会很长.我还有一些变量需要串联.

I have some strings to be concatenate and the resultant string will be quite long. I also have some variables to be concatenated.

如何组合字符串和变量,这样结果将是多行字符串?

How can I combine both strings and variables so the result would be a multi line string?

以下代码引发错误.

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" ;

请提出一种方法.

推荐答案

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

There are several ways. A simple solution is to add parenthesis:

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

如果要将每个行"放在单独的行上,则可以添加换行符:

If you want each "line" on a separate line you can add newline characters:

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

这篇关于在多行中串联python中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆