如何在字符串中的数字之前创建新行



我想在数字之前剪掉字符串,这样它就会形成一个新字符串。 我将确保除了步骤之外没有其他数字(例如用于测量(。

例:

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

使用正则表达式

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

最新更新