gpt4 book ai didi

python - 如何从 Python 中的字符串开头删除特殊字符

转载 作者:行者123 更新时间:2023-11-28 20:10:27 26 4
gpt4 key购买 nike

我从 XML 中获取数据,有时可能会在开头包含特殊字符,例如:

'This is a sample title or %&*I don't know if this is the text

我试过:title[0].isstring() 或 title[0].isdigit() 然后删除字符。但是,如果开头有多个特殊字符,那么如何删除它呢?我需要 for 循环吗?

最佳答案

你可以使用正则表达式:

import re
mystring = re.sub(r"^\W+", "", mystring)

这会删除字符串开头的所有非字母数字字符:

解释:

^   # Start of string
\W+ # One or more non-alphanumeric characters

关于python - 如何从 Python 中的字符串开头删除特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7358494/

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