我想在数字前截断字符串,这样它将形成一个新字符串。我将确保除步骤外没有其他数字(例如用于测量)。
示例:
a = 'HOW TO COOK RICE - Chapter 1: 1 rinse water once 2 add one and a half cup of water for every cup of rice 3 cover the pot and simmer'
结果应在除章节数字之外的所有数字前换行
HOW TO COOK RICE - Chapter 1
1 rinse water once
2 add one and a half cup of water for every cup of rice
3 cover the pot and simmer
答案 0 :(得分:0)
使用正则表达式
a = 'HOW TO COOK RICE - Chapter 1: 1 rinse water once 2 add one and a half cup of water for every cup of rice 3 cover the pot and simmer'
idx=[i.start() for i in re.finditer('(\d{1,} \w{1,})', a)]
if idx:
print(a[:idx[0]])
else:
print(a)
for i,index in enumerate(idx):
if not i==len(idx)-1:
print(a[index:idx[i+1]])
else:
print(a[idx[i]:])
输出
HOW TO COOK RICE - Chapter 1:
1 rinse water once
2 add one and a half cup of water for every cup of rice
3 cover the pot and simmer