简体   繁体   English

使用正则表达式从字符串中删除字符

[英]Using regular expression to remove characters from string

There is a practice problem in the book im reading which asks you to create a function which defaults to removing white space from a string and if you give it a character as an argument it removes that character from the string (basically recreating the strip method).我正在阅读的书中有一个练习问题,它要求您创建一个 function,它默认从字符串中删除空格,如果您给它一个字符作为参数,它会从字符串中删除该字符(基本上是重新创建 strip 方法) . I have written something which I think should work, it can remove the white space but wont remove the character argument i put in, it just doesn't print to the console.我写了一些我认为应该工作的东西,它可以删除空格但不会删除我输入的字符参数,它只是不会打印到控制台。

import re 

def re_move(text,chars=0):
    string_regexx = re.compile(r"\S+")
    chars_regexx = re.compile(r"^chars") 

    if chars == 0:
        f1 = string_regexx.findall(text)
        return "".join(f1)


    elif chars != 0:
        e1 = chars_regexx.findall(text)
        return " ".join(e1)

#should remove white space
print(re_move("tokyo is in japan"))

#should remove all e values
print(re_move("hello there","e"))

There is no error but the expected string with the removed e values is not output onto the console and I dont know why?没有错误,但删除 e 值的预期字符串不是 output 到控制台上,我不知道为什么?

The easiest way to remove white space from a string, text is:从字符串text中删除空格的最简单方法是:

text = re.sub(r'\s+', '', text)

Likewise, to remove, for example, characters 'a' and 'b':同样,要删除例如字符“a”和“b”:

text = re.sub('[ab]+', '', text)

To test for an optional parameter, chars , it is usual to specify a default value of None :要测试可选参数chars ,通常指定默认值None

import re

def re_move(text, chars=None):
    text = re.sub(r'\s+', '', text)
    if chars:
        text = re.sub(f'[{chars}]+', '', text)
    return text

print(re_move('abc def ghi ', chars='beh'))

Prints:印刷:

acdfgi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM