本文介绍了Python:使用正则表达式剥离函数定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个编程初学者,阅读《用Python自动化无聊的东西》这本书.在第7章中,有一个项目实践:strip(的正则表达式版本).我下面的代码不起作用(我使用Python 3.6.1).有人可以帮忙吗?

I am a very beginner of programming and reading the book "Automate the boring stuff with Python'. In Chapter 7, there is a project practice: the regex version of strip(). My code below does not work (I use Python 3.6.1). Could anyone help?

import re

string = input("Enter a string to strip: ")
strip_chars = input("Enter the characters you want to be stripped: ")

def strip_fn(string, strip_chars):
    if strip_chars == '':
        blank_start_end_regex = re.compile(r'^(\s)+|(\s)+$')
        stripped_string = blank_start_end_regex.sub('', string)
        print(stripped_string)
    else:
        strip_chars_start_end_regex = re.compile(r'^(strip_chars)*|(strip_chars)*$')
        stripped_string = strip_chars_start_end_regex.sub('', string)
        print(stripped_string)

推荐答案

您还可以使用 re.sub 来替换开头或结尾的字符.让我们说如果字符是'x'

You can also use re.sub to substitute the characters in the start or end.Let us say if the char is 'x'

re.sub(r'^x+', "", string)
re.sub(r'x+$', "", string)

第一行是lstrip,第二行是rstrip这看起来更简单.

The first line as lstrip and the second as rstripThis just looks simpler.

这篇关于Python:使用正则表达式剥离函数定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:40