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()
相关推荐
灿飞屋11 分钟前
Kotlin与Java虚拟机三:控制流
android·java·开发语言·后端·python·kotlin·安卓
benchmark_cc15 分钟前
单只股票五档盘口接入个人研究仓库:QuantDash 读取、校验与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
xiaoye-duck26 分钟前
《C++ 项目:手写大模型接入 SDK》Ollama接口设计(上):初始化、全量响应实现和测试
开发语言·网络·c++·语言模型
疯华整猫1 小时前
我用 Trae 把 Android 内存账重算了一遍
android·性能优化·源码
总要学点什么1 小时前
第98篇:三维特效-材质线效果——给一条线换十种材质,虚线的图案只填了一半
开发语言·前端·javascript·ecmascript·gis·webgl·材质
田甲2 小时前
做一款 Type-C 母座读卡器:GL3224 双卡方案实测
c语言·开发语言
青少儿编程课堂2 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中缀表达式求值解析
c++·python·算法·bfs·信息学竞赛
严肃小白兔2 小时前
MATLAB 绘图与科研论文插图制作:图形设计、统计表达与矢量导出
开发语言·matlab·科研绘图
TimeFine3 小时前
AI 编程工作流的设计:从人工判断到 AI裁判
android·ai编程
阿杰m3 小时前
Android源码第四章:Android 系统启动——App 的第一行代码从哪来?
android