Python多行字符串

时间:2020-02-23 14:43:02  来源:igfitidea点击:

有时我们有一个很长的字符串,我们想将其写成多行以提高代码的可读性。
Python提供了多种创建多行字符串的方法。

使用三引号的Python多行字符串

如果长字符串包含换行符,则可以使用三引号将它们写成多行。
请注意,三引号中包含的所有内容都是字符串值,因此,如果长字符串包含许多换行符,则可以使用它将它们分成多行。

假设我们有一个很长的字符串,如下所示:

s = 'My Name is hyman.\nI am the owner of theitroad.local\ntheitroad is a very popular website in Developers community.'

我们可以使用三引号将其编写如下:

s = """My Name is hyman.
I am the owner of theitroad.local
theitroad is a very popular website in Developers community."""

但是,如果字符串没有换行符,那还有其他方法可以将它们写成多行。

使用括号的多行字符串

我们可以使用方括号将字符串分成多行。

s = ("My Name is hyman. "
   "I am the owner of theitroad.local and "
   "theitroad is a very popular website in Developers community.")
print(s)

输出:

My Name is hyman. I am the owner of theitroad.local and theitroad is a very popular website in Developers community.

使用反斜线的多行字符串

s = "My Name is hyman. " \
  "I am the owner of theitroad.local and " \
  "theitroad is a very popular website in Developers community."
print(s)

使用join()的Python多行字符串

我们还可以使用字符串join()函数将字符串分成多行。
请注意,在方括号或者反斜杠中,我们必须自己注意空格,如果字符串确实很长,则检查空格或者双倍空格可能是一场噩梦。
我们可以使用join()函数消除它,如下所示。

s = ' '.join(("My Name is hyman. I am the owner of",
            "theitroad.local and",
            "theitroad is a very popular website",
            "in Developers community."))
print(s)