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()
相关推荐
RSABLOCKCHAIN4 小时前
AI Agents in LangGraph-2
人工智能·python
WA内核拾荒者5 小时前
WhatsApp 账号异常检测的自动化告警系统设计
数据库·python·自动化
码流怪侠5 小时前
【GitHub】Bend:让 GPU 并行编程像写 Python 一样简单
python·github
魔力女仆5 小时前
分享一个 JS 鼠标跟随贪吃蛇背景库
开发语言·javascript·计算机外设
2401_894915536 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity
麻瓜老宋7 小时前
AI开发C语言应用按步走,表达式计算器calc的第二十二步,分号赋值链式修复、TOKEN_ASSIGN
c语言·开发语言·atomcode
solo_997 小时前
用 LSPosed 模拟录屏音频编码器卡顿:从思路到落地
android
zzq77978 小时前
别把大模型 API Key 写进 APK:移动 AI 应用接口防盗刷实践
android·人工智能·安全·app加固·御盾安全·安卓加固
zhiSiBuYu05178 小时前
Python3 模块开发与应用实战指南
python