用星号更改句子中的每个单词

时间:2013-09-29 15:51:39

标签: python python-2.7

我希望句子中的每个单词都用星号更改,我试图在这里使用一行代码,但我不知道如何获得每个单词的星号

from string import join, split
def asterisk(s):
        return  join(map(lambda x: x[:0], split(s)), " * ")

print asterisk("lame af sentence")

输出:

 *  * 

您可能会注意到split()之后只更改了2个字。我曾尝试使用 lambda函数x = " * "分配给星号,但它不支持这种方式。

所以,任何帮助都会受到赞赏,提前谢谢!

4 个答案:

答案 0 :(得分:2)

您的代码在每个联接之间加上星号。单词之间有2个连接,所以有两个星号。

我想你想要

 join(map(lambda x: "*", split(s)), " ")

答案 1 :(得分:2)

您可以在此处使用str.splitstr.join

>>> strs = "lame af sentence"
>>> ' '.join('*'*len(strs.split()))
'* * *'

此处str.split将字符串拆分为空格并返回一个列表:

>>> spl = strs.split()
>>> spl
['lame', 'af', 'sentence']

现在使用此列表的长度和str.join,我们可以这样做:

>>> ' '.join("*"*len(spl))
'* * *'

如果你想保留白色空格,正则表达式可能会有所帮助:

>>> import re
>>> strs = "lame af        sentence"
>>> re.sub(r'\S+', '*', strs)
'* *        *'

答案 2 :(得分:1)

这是你可以使用的另一个:

def asterisk(s):
    return ' '.join(['*' for word in s.split()])

print asterisk("lame af sentence")

答案 3 :(得分:1)

请按照以下步骤操作:

  1. 计算您拥有的字数: words=len(s.split())
  2. 添加一个*,后跟每个字词的空格: for i in range(words): out+='* '
  3. 剪切最后一个空格: out=out[:-1]
  4. 在一行中:return '* '.join([i for i in range(len(s.split()))])[:-1]