首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将`1 `替换为`1`

将`1 `替换为`1`
EN

Stack Overflow用户
提问于 2018-01-10 12:34:27
回答 2查看 66关注 0票数 1

假设有这样一个列表

代码语言:javascript
复制
l = ['1\xa0My Cll to Adventure: 1949–1967',
 '2\xa0Crossing the Threshold: 1967–1979',
 '3\xa0My Abyss: 1979–1982',
 '4\xa0My Rod of Trils: 1983–1994',
 '5\xa0The Ultimte Boon: 1995–21',
 '6\xa0Returning the Boon: 211–215',
 '7\xa0My Lst Yer nd My Gretest Chllenge: 216–217',
 '8\xa0Looking Bck from  Higher Level']

我想要的结果是

代码语言:javascript
复制
[' 1.My Cll to Adventure: 1949–1967',
 ' 2.Crossing the Threshold: 1967–1979',
 ' 3.My Abyss: 1979–1982',
 ' 4.My Rod of Trils: 1983–1994',
 ' 5.The Ultimte Boon: 1995–21',
 ' 6.Returning the Boon: 211–215',
 ' 7.My Lst Yer nd My Gretest Chllenge: 216–217',
 ' 8.Looking Bck from  Higher Level']

我试着用代码

代码语言:javascript
复制
import re
In [114]: [re.sub(r'\d\xa0', r' \d.', i) for i in l]
Out[114]:
[' \\d.My Cll to Adventure: 1949–1967',
 ' \\d.Crossing the Threshold: 1967–1979',
 ' \\d.My Abyss: 1979–1982',
 ' \\d.My Rod of Trils: 1983–1994',
 ' \\d.The Ultimte Boon: 1995–21',
 ' \\d.Returning the Boon: 211–215',
 ' \\d.My Lst Yer nd My Gretest Chllenge: 216–217',
 ' \\d.Looking Bck from  Higher Level']

它不能像我想要的那样用数字代替。

如何完成这样的任务?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-01-10 12:41:12

在句号之前,你没有捕捉到你想要的数字。为此,我们只需要在要捕获的数字周围使用括号,然后使用它们的捕获组id引用它们,即1

通过以下方式:

代码语言:javascript
复制
l = ['1\xa0My Cll to Adventure: 1949–1967',
 '2\xa0Crossing the Threshold: 1967–1979',
 '3\xa0My Abyss: 1979–1982',
 '4\xa0My Rod of Trils: 1983–1994',
 '5\xa0The Ultimte Boon: 1995–21',
 '6\xa0Returning the Boon: 211–215',
 '7\xa0My Lst Yer nd My Gretest Chllenge: 216–217',
 '8\xa0Looking Bck from  Higher Level']

然后我们运行:

代码语言:javascript
复制
import re
[re.sub(r'(\d+)\xa0', r' \1.', i) for i in l]

并获得输出:

代码语言:javascript
复制
[' 1.My Cll to Adventure: 1949–1967',
 ' 2.Crossing the Threshold: 1967–1979',
 ' 3.My Abyss: 1979–1982',
 ' 4.My Rod of Trils: 1983–1994',
 ' 5.The Ultimte Boon: 1995–21',
 ' 6.Returning the Boon: 211–215',
 ' 7.My Lst Yer nd My Gretest Chllenge: 216–217',
 ' 8.Looking Bck from  Higher Level']
票数 2
EN

Stack Overflow用户

发布于 2018-01-10 13:19:22

以下是在for循环中使用string replace方法的工作原理:

代码语言:javascript
复制
outl = []
for i in l:
    outl.append(" "+i.replace("\xa0",".",1))
print(outl)

输出:

代码语言:javascript
复制
[' 1.My Cll to Adventure: 1949–1967', 
' 2.Crossing the Threshold: 1967–1979', 
' 3.My Abyss: 1979–1982', 
' 4.My Rod of Trils: 1983–1994', 
' 5.The Ultimte Boon: 1995–21', 
' 6.Returning the Boon: 211–215', 
' 7.My Lst Yer nd My Gretest Chllenge: 216–217', 
' 8.Looking Bck from  Higher Level']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48180363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档