gpt4 book ai didi

Python:在保留换行符的同时缩进除第一行以外的所有字符串行?

转载 作者:太空狗 更新时间:2023-10-29 21:21:05 30 4
gpt4 key购买 nike

我想缩进多行字符串的所有行,除了第一行,而不换行。

例如我想转:

A very very very very very very very very very very very very very very very very
long mutiline
string

进入:

A very very very very very very very very very very very very very very very very
long multiline
string

我试过了

textwrap.fill(string, width=999999999999, subsequent_indent='   ',)

但这仍然会将所有文本放在一行中。想法?

最佳答案

您只需将换行符 '\n' 替换为换行符加上空格 '\n ' 并将其保存到变量(因为replace 不会更改您的原始字符串,而是返回一个包含替换的新字符串)。

string = string.replace('\n', '\n    ')

关于Python:在保留换行符的同时缩进除第一行以外的所有字符串行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18518031/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com