python怎么引用多行输入,如何删除Python三重引用多行字符串的额外缩进?

本文介绍了一种在Python中处理用户输入脚本时遇到的问题:当用户输入包含多行字符串时,后续的自动缩进会影响到字符串本身的内容,导致每个字符串行首出现不必要的缩进。文章提供了一个解决方案,通过正则表达式去除多行字符串内部的额外缩进。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have a python editor where the user is entering a script or code, which is then put into a main method behind the scenes, while also having every line indented. The problem is that if a user has a multi line string, the indentation made to the whole script affects the string, by inserting a tab in every space. A problem script would be something so simple as:

"""foo

bar

foo2"""

So when in the main method it would look like:

def main():

"""foo

bar

foo2"""

and the string would now have an extra tab at the beginning of every line.

解决方案

So if I get it correctly, you take whatever the user inputs, indent it properly and add it to the rest of your program (and then run that whole program).

So after you put the user input into your program, you could run a regex, that basically takes that forced indentation back. Something like: Within three quotes, replace all "new line markers" followed by four spaces (or a tab) with only a "new line marker".

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值