志在逍遥 2022-05-01 10:36 采纳率: 66.7%
浏览 13
已结题

请问如何去除每行数字和空格

问题遇到的现象和发生背景

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:


  • 写回答

1条回答 默认 最新

  • Hann Yang 优质创作者: 编程框架技术领域 2022-05-01 12:06
    关注
    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:
    '''
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 5月9日
  • 已采纳回答 5月1日
  • 创建了问题 5月1日