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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2019-09-27 Mysql中的触发器
2019-09-27 Apache-dbutils 简介及事务处理
2019-09-27 阿里druid连接池监控数据自定义存储
2016-09-27 在VS 2010中使用 VS2013的解决方案
2012-09-27 FarPoint表格数字框中小数点位数的设置