【问题标题】:re.search string in python在python中重新搜索字符串
【发布时间】:2015-12-14 12:36:32
【问题描述】:

我想从这样的字符串中提取屏幕名称:

text = (u'675739242841120768', [{u'id': 9207632, u'indices': [3, 15], u'id_str': u'9207632', u'screen_name': u'brainpicker', u'name': u'Maria Popova'}])

我认为我需要使用的这段代码没有得到任何结果:

re.search("screen_name': u'(...)', u'name", text)

我不确定是否应该在括号内添加其他内容。

【问题讨论】:

  • 你的text 数据类型是什么,它看起来不像你所显示的字符串,为什么它不起作用,是否有任何错误
  • 应该是字符串
  • 你能print type(text)
  • @PedroMuñoz:但您错过了 Vignesh 所说的另一部分内容:您遇到了什么错误?
  • @VigneshKalai 它是一个元组

标签: python string search


【解决方案1】:

您需要指定准确的索引值,因为变量文本包含元组、列表、字典的组合。

>>> text = (u'675739242841120768', [{u'id': 9207632, u'indices': [3, 15], u'id_str': u'9207632', u'screen_name': u'brainpicker', u'name': u'Maria Popova'}])
>>> text[1][0]['screen_name']
u'brainpicker'

您不能将re.search 直接应用于 list 或 tuples 或 dict ,它应该接受字符串作为最后一个参数。

【讨论】:

  • 如果是字符串re.search(r"'screen_name': u'(\w+)', u'name'", text).group(1)
  • 伴侣你为什么不将你的评论添加到答案中
  • @VigneshKalai op 说这是一个元组,所以没有必要.. :-)
  • 就是这样!感谢您的帮助@AvinashRaj
猜你喜欢
  • 2016-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
  • 2020-04-12
  • 2015-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多