Python多行字符串

本文介绍了Python中创建多行字符串的几种方式,包括使用三引号、括号、反斜线以及join()函数,以提高代码可读性。特别地,当字符串不包含换行符时,可以利用括号或反斜线进行换行处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值