如何用Python中的另一个字符串替换函数中的字符串?

问题描述:

我想这样做:如何用Python中的另一个字符串替换函数中的字符串?

>>> special = 'x' 
>>> random_function('Hello how are you') 
'xxxxx xxx xxx xxx' 

我基本上要返回字符串:{(STR) - > STR}

我不断获取变量定义。

对不起,这是我的第一篇文章。

由于Python中的字符串是不可变的,每次使用replace()方法时都必须创建一个新的字符串。每次调用replace也必须遍历整个字符串。这显然是低效的,虽然在这个尺度上并不明显。

一种替代方法是使用列表包含(docs,tutorial)循环一次字符串并创建新字符列表。 isalnum()方法可以用作测试,仅用于替换字母数字字符(即留下空格,标点符号等未改动)。

最后一步是使用join()方法将字符连接到新字符串中。请注意,在这种情况下,我们使用空字符串''将它们之间的任何内容连接在一起。如果我们使用' '.join(new_chars),则每个字符之间会有一个空格,或者如果我们使用'abc'.join(new_chars),则字母abc将位于每个字符之间。

>>> def random_function(string, replacement): 
...  new_chars = [replacement if char.isalnum() else char for char in string] 
...  return ''.join(new_chars) 
... 
>>> random_function('Hello how are you', 'x') 
'xxxxx xxx xxx xxx' 

当然,你应该把这个功能比random_function()一个更合乎逻辑的名字......

这可以用正则表达式可以轻松完成:

>>> re.sub('[A-Za-z]', 'x', 'Hello how are you') 
'xxxxx xxx xxx xxx' 

def hide(string, replace_with): 
    for char in string: 
     if char not in " !?.:;": # chars you don't want to replace 
      string = string.replace(char, replace_with) # replace char by char 
    return string 

print hide("Hello how are you", "x") 
'xxxxx xxx xxx xxx' 

还检查了stringre模块。

不知道我是否应该在注释或整个答案补充呢?正如其他人所建议的,我会建议使用正则表达式,但是您可以使用\w字符来指代任何字母表中的字母。下面是完整的代码:

import re 

def random_function(string): 
    newString=re.sub('\w', 'x', string) 
    return(newString) 

print(random_function('Hello how are you')) 

应打印XXXXX XXX XXX XXX