【问题标题】:How to remove whitespace in a list如何删除列表中的空格
【发布时间】:2016-09-28 19:57:54
【问题描述】:

我无法删除列表中的空格。

invoer = "5-9-7-1-7-8-3-2-4-8-7-9"
cijferlijst = []

for cijfer in invoer:
    cijferlijst.append(cijfer.strip('-'))

我尝试了以下方法,但它不起作用。我已经从我的字符串中列出了一个列表并将所有内容分开,但 "-" 现在是 ""

filter(lambda x: x.strip(), cijferlijst)
filter(str.strip, cijferlijst)
filter(None, cijferlijst)
abc = [x.replace(' ', '') for x in cijferlijst]

【问题讨论】:

  • cijferlijst = filter(lambda x: x.strip(), cijferlijst)
  • 为什么你不用-分割文本?
  • 为什么不是cijferlijst = invoer.split("-")?我是否误解了您要做什么?
  • @MattCremeens 你确实做到了。非常感谢!
  • 很高兴我能帮上忙。

标签: python list


【解决方案1】:

试试看:

>>> ''.join(invoer.split('-'))
'597178324879'

【讨论】:

  • 为什么不replace
【解决方案2】:

如果您希望字符串中的数字不包含-,请使用.replace()

>>> string_list = "5-9-7-1-7-8-3-2-4-8-7-9"
>>> string_list.replace('-', '')
'597178324879'

如果您希望数字为list 的数字,请使用.split()

>>> string_list.split('-')
['5', '9', '7', '1', '7', '8', '3', '2', '4', '8', '7', '9']

【讨论】:

    【解决方案3】:

    这看起来很像以下问题: Python: Removing spaces from list objects

    答案是使用strip 而不是replace。你试过了吗

    abc = x.strip(' ') for x in x
    

    【讨论】:

      猜你喜欢
      • 2014-05-26
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 2013-04-06
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多