【问题标题】:How to remove spaces from a xrange list - Python如何从 xrange 列表中删除空格 - Python
【发布时间】:2015-09-07 03:46:42
【问题描述】:

假设我有:

hello = list(xrange(100))
print hello

结果是:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10...

我需要从列表中删除所有这些空格,以便它可以像:

1,2,3,4,5,6,7,8,9,10...

【问题讨论】:

  • hello 将打印一个列表对象。为什么是字符串对象?

标签: python xrange


【解决方案1】:

由于join 采用字符串对象,您需要将这些项目显式转换为字符串。例如:

hello = ','.join(list(xrange(100)))
TypeError: sequence item 0: expected string, int found

所以:

hello = xrange(100)
print ''.join([str(n) for n in hello])

请注意,不需要list()。

【讨论】:

  • 不需要列表理解。将生成器表达式传递给join
猜你喜欢
  • 2017-03-05
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 2011-06-18
  • 1970-01-01
  • 2011-03-15
相关资源
最近更新 更多