用递增的数字替换字符

2024-04-28 18:02:25 发布

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

text = "Subjects cover: Warehouse Operations;  effective communication,Speed Functions; Newton laws of motion,Fiber Communication; sea level transmission"

如何使用“;”替换先前的“;”替换找到的数字“;”替换找到的“:”,这是我要查找的输出

output="Subjects cover: 1)Warehouse Operations: effective communication 2)Speed Functions: Newton laws of motion 3) Fiber Communication: sea level transmission"

也就是说,它会在哪里找到“;“它会找到上一个”,“并用一个“数字”替换它”,然后用“;”替换后面的“;”和“:”

我一直试图用regex来做,但是代码变得非常糟糕&;非音速的


Tags: ofnewtoncoverfunctionswarehousemotioncommunicationoperations
1条回答
网友
1楼 · 发布于 2024-04-28 18:02:25

以下是一种方法:

text = "Subjects cover: Warehouse Operations;  effective communication,Speed Functions; Newton laws of motion,Fiber Communication; sea level transmission"

# split the string
t1 = text.split(':')

# modify the strings
rf = [[y.replace(';', ':').strip() for y in x.split(',')] for i, x in enumerate(t1[1:])][0]

# join the results
result = t1[0] + ' ' +  ' '.join([f'{i}) {x}' for i,x in enumerate(rf, 1)])

print(result)

'Subjects cover 1) Warehouse Operations:  effective communication 2) Speed Functions: Newton laws of motion 3) Fiber Communication: sea level transmission'

相关问题 更多 >