在字符串列表中使用正则表达式删除字符

时间:2017-01-16 22:44:12

标签: python regex

我有一个包含2个项目的列表:

body = ['''Customer formerly known as ALEX tel # 123 . 123123 123
word word word word ...''', '12323']

我正在尝试使用正则表达式删除空格,并且只留下第1项中文本的单词。我可以删除但不通过列表。我收到错误。

for j, item in enumerate(body):
    test = re.sub(r'[^A-Za-z-]+', ' ', body[0])
    item[0] = test
    print(item)

我希望将新列表替换为:

['''Customer formerly known as ALEX tel word word word word''', '12323']
Traceback (most recent call last) <ipython-input-107-301fe3075791> in <module>()
      6 for j, item in enumerate(body):
      7     test = re.sub(r'[^A-Za-z-]+', ' ', body[0])
----> 8     item[0] = test
      9     print(item)
     10 
TypeError: 'str' object does not support item assignment

1 个答案:

答案 0 :(得分:0)

item是一个字符串(想想"hello"

"hello"[2] = '5' 

不是允许的操作...调试此类事情的好方法是使用print(例如print item发生错误之前)

解决了您收到错误的原因,但您的代码还有其他一些问题(例如,请参阅jonrsharps评论)

相关问题