Python 2.7 在python中获取两个字符之间的子字符串的最佳方法是什么?

Python 2.7 在python中获取两个字符之间的子字符串的最佳方法是什么?,python-2.7,substring,Python 2.7,Substring,我到处都找过了,但似乎找不到一种简单的方法来获取python中的子字符串 我正在使用tweepy,我已经将tweepy tweet存储到textblob数组中,并将textblob设置为字符串变量 例如: RT@Acosta:特朗普为他对夏洛茨维尔的“非常好的人”评论辩护:“人们在那里抗议拆除纪念碑 这是一条推特,我想要@acostator Acosta部分, 我该如何将该部分分串 我试着使用re库,虽然它在任何其他字符串上都能正常工作,但在tweet上却不起作用 match = re.sea

我到处都找过了,但似乎找不到一种简单的方法来获取python中的子字符串

我正在使用tweepy,我已经将tweepy tweet存储到textblob数组中,并将textblob设置为字符串变量

例如: RT@Acosta:特朗普为他对夏洛茨维尔的“非常好的人”评论辩护:“人们在那里抗议拆除纪念碑

这是一条推特,我想要@acostator Acosta部分, 我该如何将该部分分串

我试着使用re库,虽然它在任何其他字符串上都能正常工作,但在tweet上却不起作用


match = re.search("\@(.*?)\:" , randTweet).group(1)

您可以使用split执行以下操作:

综合起来:

>>> person = test.split('@')[1].split(':')[0]
>>> person
'Acosta'
Python脚本


在拆分提及之前,您应该进行一些错误检查以确认是否找到提及。

无法复制您的问题。修复后

SyntaxError:第3行main.py文件中的非ASCII字符“\xe2”,但未声明编码;有关详细信息,请参阅

由于您的数据包括“和”和…它可以工作:

randTweet = """RT @Acosta: Trump defends his "very fine people" comments on Charlottesville: "People were there protesting the taking down of the monument..." """

import re

match = re.search("\@(.*?)\:" , randTweet).group(1)
print(match) # Acosta
test = '"RT @Acosta: Trump defends his “very fine people” comments on Charlottesville: “People were there protesting the taking down of the monument…"'

mention = test.split('@')
person = mention[1].split(':')

print(person[0])
randTweet = """RT @Acosta: Trump defends his "very fine people" comments on Charlottesville: "People were there protesting the taking down of the monument..." """

import re

match = re.search("\@(.*?)\:" , randTweet).group(1)
print(match) # Acosta