【问题标题】:Converting a list into a string将列表转换为字符串
【发布时间】:2013-07-04 14:20:50
【问题描述】:

我不断地获取用户输入的字符串,然后尝试删除任何不是字符或数字的字符。

我开发的方法是用空格分割字符串,然后分析每个单词以查找无效字符。

我很难将单词重新组合在一起,每个单词之间都有空格。我试过使用 ' '.join(list) 但它会在每个字符或数字之间放置一个空格。

【问题讨论】:

  • 您可以简单地使用''.join(string) 而不是' '.join(string)。 (但您的具体问题可以更容易解决)
  • 此代码不起作用。第一个 while 后面没有任何缩进
  • 我在这里复制并粘贴了我的代码,但我不得不使用 4 个空格缩进。我的一些标签没有显示出来。

标签: python string list function join


【解决方案1】:

基于简单循环的解决方案:

strs = "foo12 #$dsfs 8d"
ans = []
for c in strs:
    if c.isalnum():
        ans.append(c)
    elif c.isspace():  #handles all types of white-space characters \n \t etc.
        ans.append(c)
print ("".join(ans))
#foo12 dsfs 8d

单行:

使用str.translate:

>>> from string import punctuation, whitespace
>>> "foo12 #$dsfs 8d".translate(None,punctuation)
'foo12 dsfs 8d'

同时删除空白:

>>> "foo12 #$dsfs 8d".translate(None,punctuation+whitespace)
'foo12dsfs8d'

regex:

>>> import re
>>> strs = "foo12 #$dsfs 8d"
>>> re.sub(r'[^0-9a-zA-Z]','',strs)
'foo12dsfs8d'

使用str.joinstr.isalnumstr.isspace

>>> strs = "foo12 #$dsfs 8d"
>>> "".join([c for c in strs if c.isalnum() or c.isspace()])
'foo12 dsfs 8d'

【讨论】:

  • 我不认为我可以使用翻译。是否有可能以另一种方式做到这一点?
  • @HarryHarry str.translate 有什么问题?
  • 这是我教授的规矩。如果我们没有在课堂上讲过它,那么它就不能被使用。
  • @HarryHarry 看我的更新解决方案,你能用str 方法吗?
  • @HarryHarry 请注意:如果您包含有关您被允许使用的内容和任何限制的信息会很好,以免浪费试图帮助您的人们的时间。事实上 - 我会建议 editing your question now 包含此类信息;)
【解决方案2】:

当然,@Ashwini 的回答比这个要好,但是如果你还是想用循环来做的话

strings = raw_input("type something")
while(True):
    MyString = ""
    if strings == "stop": break
    for string in strings.split():
        for char in string:
            if(char.isalnum()): MyString += char
        MyString += " "
    print MyString
    strings = raw_input("continue : ")

样本运行

$ python Test.py
type somethingWelcome to$%^ Python
Welcome to Python 
continue : I love numbers 1234 but not !@#$
I love numbers 1234 but not  
continue : stop

编辑

Python 3 版本:

正如 cmets 中的 Ashwini 所指出的,将字符存储在列表中并在末尾打印带有 join 的列表。

strings = input("type something : ")
while(True):
    MyString = []
    if strings == "stop": break
    for string in strings.split():
        for char in string:
            if(char.isalnum()): MyString.append(char)
        MyString.append(" ")
    print (''.join(MyString))
    strings = input("continue : ")

示例运行:

$ python3 Test.py
type something : abcd
abcd 
continue : I love Python 123
I love Python 123 
continue : I hate !@#
I hate  
continue : stop

【讨论】:

  • 我运行了您的代码并得到了不同的输出。是因为我用的是python 3吗?
  • 请注意,使用++= 完成的字符串连接相当in-efficient,将字符附加到列表并在末尾使用连接。
  • @HarryHarry 将raw_input 替换为input 并在py3.x 中使用print 作为函数
  • @AshwiniChaudhary 谢谢 yaar :) 在 Python3 版本中也包含了您的 cmets。
  • @HarryHarry 用 python3 版本更新了解决方案。请检查
【解决方案3】:

这是我的解决方案。有关详细信息,请参阅 cmets:

def sanitize(word):
    """use this to clean words"""
    return ''.join([x for x in word if x.isalpha()] )

n = input("type something")

#simpler way of detecting stop
while(n[-4:] != 'stop'):
    n += "  " + input("continue : ")

n = n.split()[:-1]
# if yuo use list= you are redefining the standard list object
my_list = [sanitize(word) for word in n]

print(my_list)
strn = ' '.join(my_list)
print(strn)

【讨论】:

    【解决方案4】:

    您可以通过连接和列表推导来做到这一点。

    def goodChars(s):
      return " ".join(["".join([y for y in x if y.isdigit() or y.isalpha()]) for x in s.split()])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多