如何解决如何删除尖括号python中的所有字符?
如何删除尖括号内的所有字符,包括字符串中的括号?我怎样才能删除 ("\r\n") 和 ("."+"any 3 characters") 之间的所有文本 这可能吗?我目前正在使用@xkcdjerry 的解决方案
例如
body = """Dear Students roads etc. you place a tree take a snapshot,then when you place a\r\nbuilding,take a snapshot. Place at least 5-6 objects and then have 5-6\r\nsnapshots. Please keep these snapshots with you as everyone will be asked\r\nto share them during the class.\r\n\r\nI am attaching one PowerPoint containing instructions and one video of\r\nexplanation for your reference.\r\n\r\nKind regards,\r\nTeacher Name\r\n zoom_0.mp4\r\n<https://drive.google.com/file/d/1UX-klOfVhbefvbhZvIWijaBdQuLgh_-Uru4_1QTkth/view?usp=drive_web>"""
d = re.compile("\r\n.+?\\....")
body = d.sub('',body)
a = re.compile("<.*?>")
body = a.sub('',body)
print(body)```
For some reason the output is fine except that it has:
```gle.com/file/d/1UX-klOfVhbefvbhZvIWijaBdQuLgh_-Uru4_1QTkth/view?usp=drive_web>
随机附在最后怎么解决。
解决方法
答案
您的问题可以通过正则表达式解决:
将其放入外壳中:
import re
a=re.compile("<.*?>")
a.sub('',"Keep this part of the string< Remove this part>Keep This part as well")
输出:
'Keep this part of the stringKeep This part as well'
第二个问题:
import re
re.compile("\r\n.*?\\..{3}")
a.sub('',"Hello\r\nFilename.png")
输出:
'Hello'
故障
Regex 是一种强大的方法,可以在较大的字符串中查找、替换和变异小字符串,如需进一步阅读,请参阅 https://docs.python.org/3/library/re.html。同时,以下是此答案中使用的正则表达式信息的细分:
.
表示任何字符。*?
表示根据需要尽可能多但尽可能少(非贪婪匹配)
所以 .*?
表示任意数量的字符,但尽可能少。
注意:第二个正则表达式中有 \\.
的原因是匹配中的 .
需要用 \
转义,而\\
需要转义为 {{ 1}}
方法:
re.compile(patten:str)
编译一个正则表达式以供进一步使用。
regex.sub(repl:str,string:str)
用 repl 替换 regex
中 string
的每个匹配项。
希望有帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。