pycharm里创建一个python文件,写入如下代码
# -*- coding: utf-8 -*-
new_line='''
1 people = 30
2 cars = 40
3 trucks = 15
4 #111注释111
5
6 if cars > people:
7 print("We should take the cars.")
8 elif cars < people:
9 print("We should not take the cars.")
10 else:
11 print("We can't decide.")
12
13 if trucks > cars:
'''
我想实现正则选择打印new_line,去除里面开头的数字和空格,效果如下
people = 30
cars = 40
trucks = 15
#111注释111
if cars > people:
print("We should take the cars.")
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide.")
if trucks > cars:
import re
new_line='''
1 people = 30
2 cars = 40
3 trucks = 15
4 #111注释111
5
6 if cars > people:
7 print("We should take the cars.")
8 elif cars < people:
9 print("We should not take the cars.")
10 else:
11 print("We can't decide.")
12
13 if trucks > cars:
'''
t = new_line.split('\n')
for i,line in enumerate(t):
if t[i]:
t[i]=re.sub(r"\d+[ ]{0,3}", "", line, count=1)
print('\n'.join([i for i in t if i]))
'''--result:
people = 30
cars = 40
trucks = 15
#111注释111
if cars > people:
print("We should take the cars.")
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide.")
if trucks > cars:
'''