贫民窟里的程序高手

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Sometimes we have a very long string and we want to write it into multiple lines for better code readability. Python provides various ways to create multiline strings.

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

使用三引号的Python多行字符串 (Python Multiline String using triple quotes)

If your long string has newline characters, then you can use triple quotes to write them into multiple lines. Note that anything goes inside triple quotes is the string value, so if your long string has many newline characters then you can use it to split them into multiple lines.

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

 
 

Let’s say we have a long string as follows:

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

s = 'My Name is Pankaj.\nI am the owner of JournalDev.com\nJournalDev is a very popular website in Developers community.'

We can write it using triple quotes as follows:

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

s = """My Name is Pankaj.
I am the owner of JournalDev.com
JournalDev is a very popular website in Developers community."""

But what if the string doesn’t have newline characters, then there are other ways to write them in multiple lines.

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

 
 

使用括号的多行字符串 (Multiline string using brackets)

We can split a string into multiple lines using brackets.

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

s = ("My Name is Pankaj. "
     "I am the owner of JournalDev.com and "
     "JournalDev is a very popular website in Developers community.")
print(s)

Output:

输出:

My Name is Pankaj. I am the owner of JournalDev.com and JournalDev is a very popular website in Developers community.

使用反斜线的多行字符串 (Multiline string using backslash)

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

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

We can also split a string into multiple lines using string join() function. Note that in brackets or backslash way, we have to take care of spaces yourself and if the string is really long then it can be a nightmare to check for spaces or double spaces. We can get rid of that using join() function as shown below.

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

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

GitHub RepositoryGitHub存储库中检出完整的python脚本和更多Python示例。

翻译自: https://www.journaldev.com/23864/python-multiline-string

 

posted on 2022-09-27 10:01  贫民窟里的程序高手  阅读(359)  评论(0编辑  收藏  举报