python - 删除不确定的子串

标签 python string

我对 python 比较陌生。假设我有以下字符串 -

tweet1= 'Check this out!! #ThrowbackTuesday I finally found this!!'
tweet2= 'Man the summer is hot... #RisingSun #SummerIsHere Can't take it..'

现在,我正在尝试删除推文中的所有 hashtags(#),这样 -

tweet1= 'Check this out!!  I finally found this!!'
tweet2= 'Man the summer is hot...  Can't take it..'

我的代码是 -

tweet1= 'Check this out!! #ThrowbackTuesday I finally found this!!'
i,j=0,0
s=tweet1
while i < len(tweet1):
    if tweet1[i]=='#':
        j=i
        while tweet1[j] != ' ':
            ++j
        while i<len(tweet1) and j<len(tweet1):
            ++j
            s[i]=tweet1[j]
            ++i
    ++i
print(s)

这段代码没有输出,也没有错误,这让我相信我使用了错误的逻辑。使用正则表达式有更简单的解决方案吗?

最佳答案

这是一个正则表达式解决方案:

re.sub(r'#\w+ ?', '', tweet1)

正则表达式意味着删除一个哈希符号,后跟 1 个或多个单词字符(字母、数字或下划线),可选地后跟一个空格(这样您就不会连续得到两个空格)。

您可以通过 Google 在 Python 中找到很多关于正则表达式的一般信息,这并不难。

此外,要允许其他特殊字符,例如 $@,请将 \w 替换为 [\w$@ ],其中 $@ 可以替换为您喜欢的任何字符,即括号中的所有内容都是允许的。

关于python - 删除不确定的子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36219880/

相关文章:

python - 尝试使用 Django 发送电子邮件时出现 "[Errno 101] Network is unreachable"

python - 从 biopython 远程爆破

python - AES Python 加密和 Ruby 加密 - 不同的行为?

string - 将字符串与模式匹配并提取值的好方法是什么?

Java正则表达式在任何字符串中查找字符

c - 使用 C 查找字符串中的所有回文

c++ - 如何正确读取和解析标准输入 C++ 中的整数字符串

python - 使用 Python twisted 在 linux 上将 HID 访问与 evdev 集成

python - matplotlib 中错误的 latex 渲染

java - 获取列表中特定字符串的最后一次出现