3

我想做这个:

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

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

我不断得到未定义的变量。

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

4

4 回答 4

4

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

>>> re.sub('[A-Za-z]', 'x', 'Hello how are you')
'xxxxx xxx xxx xxx'
于 2012-10-13T19:41:46.943 回答
4

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

一种替代方法是使用列表综合(文档教程)循环遍历字符串一次并创建新字符列表。该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()...更合乎逻辑的名字。

于 2012-10-13T21:25:08.527 回答
2
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模块。

于 2012-10-13T20:40:23.607 回答
0

不确定我是否应该在评论或整个答案中添加这个?正如其他人建议的那样,我建议使用正则表达式,但您可以使用该\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

于 2016-03-30T16:15:14.563 回答