python 三引号

文章目录

三引号字符串会原样保留换行和空格

"""""" 是空字符串

python 复制代码
s = """"""
print(s)
print(repr(s)) # 输出: ''

三引号会保留换行。

开头3引号不紧跟内容会多一个换行。内容结束回车后在写3引号,也会多一个换行

。

python 复制代码
s = """
hello
world
"""
print(s)
print("***************")
print(repr(s))

如果不想要开头的换行,可以这样写:""" \ 后面的反斜杠可以去掉三引号后的第一个换行.或者紧跟内容

python 复制代码
s = """hello
world
"""
print(repr(s))
# 结果:
"""
hello
world

*******
'hello\nworld\n'
"""

或者这样:

python 复制代码
s = """\
hello
world
"""
print(s)
print("*******")
print(repr(s))
# 结果:
"""
hello
world

*******
'hello\nworld\n'
"""

如果不像要结尾的换行,可以结尾的三引号紧跟内容

python 复制代码
s = """
hello
world"""
print(s)
print("*******")
print(repr(s))
# 结果:
"""

hello
world
*******
'\nhello\nworld'
"""

结尾有换行是因为,结尾打了回车

第一个\n:是jkl这一行结束

第一个\n:是空白行结束

python 复制代码
s = """
abc
def
"""
print(s)
print("****")
print(repr(s))
print("----------------------")
ss = """
ghi
jkl

"""
print(ss)
print("@@@@@@@@@@")
print(repr(ss))

三引号会保留缩进空格

python 复制代码
def demo():
    s = """
    hello
    world
    """
    print(s)
    print("*****")
    print(repr(s))

demo()
# 结果:
"""

    hello
    world
    
*****
'\n    hello\n    world\n    '
"""

想让内容顶格,有三种常见写法

写法一:内容真的顶格写.但是在函数里面,这样写不太好看
python 复制代码
s = """hello
world"""
print(s)
print("********")
print(repr(s))

函数里面这么写不好看

python 复制代码
def demo():
    s = """hello
world"""
    print(s)
    print("*****")
    print(repr(s))
demo()
写法二:用 textwrap.dedent() 去掉公共缩进
python 复制代码
import textwrap

def demo():
    s = textwrap.dedent("""
        hello(缩进8个)
        world(缩进8个)
            ni(缩进12个)
        hao(缩进8个)
                ya(缩进16个)
    """)
    print(s)
    print("******")
    print(repr(s))
demo()
写法三:用 .strip() 去掉首尾空行。.strip() 只去掉首尾空白,不会去掉每一行前面的缩进
python 复制代码
s = """
hello
world
""".strip()
print(s)
print("******")
print(repr(s))

.strip() 只去掉首尾空白,不会去掉每一行前面的缩进

python 复制代码
s = """
    hello
    world
""".strip()
print(s)
print("******")
print(repr(s))


总结 推荐用textwrap去掉公共缩进,用strip去掉首尾空行、首尾空格
python 复制代码
import textwrap
def demo():
    s = textwrap.dedent("""
        hello(缩进8个)
        world(缩进8个)
            ni(缩进12个)
        hao(缩进8个)
                ya(缩进16个)
    """).strip()
    print(s)
    print("******")
    print(repr(s))

demo()
相关推荐
我就是不信12 分钟前
Java8 lambda 表达式 forEach 如何提前终止?
开发语言·windows·python
Cx330❀13 分钟前
深入浅出 Qt 绘图机制:从 QPainter 到四大图像类解析
开发语言·qt·ui·性能优化·图形渲染
全栈弄潮儿19 分钟前
Python实战第9期:文件操作
后端·python·编程语言
小星星_ios24 分钟前
从 3Blue1Brown 到 NumPy:手写一个神经网络训练 MNIST
人工智能·python·神经网络
老牛日常随笔25 分钟前
Google把Android测试搬进AI对话:ARTEMIS如何用自然语言操作你的手机
android·人工智能·智能手机
信可维25 分钟前
AI 读 Word 表格总读错?先查合并单元格和表头这 3 处
开发语言·人工智能·c#·word·软件工程
Maxwin27 分钟前
Manim 竖屏画布选 9×16 还是 4.5×8?从 font_size 和每单位像素数说起
python·ffmpeg
昭昭日月明34 分钟前
使用 Ragas 量化 RAG
python·langchain·ai编程
姜九笙56139 分钟前
python学习---归来仍是新人
java·python·学习
HEJOO91 小时前
Java 并发运行中的安全问题详解
java·开发语言