将“1”替换为“1”`

2024-09-30 03:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有这样一张单子

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']

我想要的结果是

[' 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']

我试过密码

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']

它没能像我想的那样用数字代替。你知道吗

如何完成这样的任务?你知道吗


Tags: ofthetothresholdmyadventurelstrod
2条回答

for循环中使用stringreplace方法的以下工作:

outl = []
for i in l:
    outl.append(" "+i.replace("\xa0",".",1))
print(outl)

输出:

[' 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']

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

使用:

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']

然后我们运行:

import re
[re.sub(r'(\d+)\xa0', r' \1.', i) for i in l]

并得到输出:

[' 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']

相关问题 更多 >

    热门问题