Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将函数的参数放入原始字符串中_Python_Regex_String_Variables - Fatal编程技术网

Python 如何将函数的参数放入原始字符串中

Python 如何将函数的参数放入原始字符串中,python,regex,string,variables,Python,Regex,String,Variables,我想创建一个函数来删除文本字符串中的字符。 我将传递文本字符串和字符作为函数的参数。 该函数工作正常,但如果我想将其作为原始字符串进行威胁,我不知道如何正确执行 例如: import re def my_function(text, ch): Regex=re.compile(r'(ch)') # <-- Wrong, obviously this will just search for the 'ch' characters print(Regex.sub

我想创建一个函数来删除文本字符串中的字符。 我将传递文本字符串和字符作为函数的参数。 该函数工作正常,但如果我想将其作为原始字符串进行威胁,我不知道如何正确执行

例如:

import re

def my_function(text, ch):    
    Regex=re.compile(r'(ch)')   # <-- Wrong, obviously this will just search for the 'ch' characters
    print(Regex.sub('',r'text'))      # <-- Wrong too, same problem as before. 


text= 'Hello there'
ch= 'h'

my_function(text, ch)
重新导入
def my_功能(文本,通道):
Regex=re.compile(r'(ch)#如何更改:

Regex=re.compile(r'(ch)')
print(Regex.sub('',r'text'))
致:

但是,更简单的方法是使用
str.replace()
作为:

text= 'Hello there'
ch= 'h'
text = text.replace(ch, '')
# value of text: 'Hello tere'
改变一下怎么样:

Regex=re.compile(r'(ch)')
print(Regex.sub('',r'text'))
致:

但是,更简单的方法是使用
str.replace()
作为:

text= 'Hello there'
ch= 'h'
text = text.replace(ch, '')
# value of text: 'Hello tere'
这将用空字符串替换所有出现的ch。在这种情况下,不需要调用正则表达式的开销


这将用空字符串替换所有出现的ch。在这种情况下,不需要调用正则表达式的开销。

谢谢,我正在阅读的那本书还没有提到使用“格式”方法的替代方法。我想我今天学到了一些新东西。谢谢,我要看的那本书还没有提到使用“格式”方法的替代方法。我想我今天学到了一些新东西。是的,谢谢。这是一个更简单有效的方法。是的,谢谢。这是一种更简单有效的方法。