【问题标题】:Remove \xa0 from string using in Python在 Python 中使用从字符串中删除 \xa0
【发布时间】:2017-05-16 13:26:32
【问题描述】:

我有一个价格列表,我想从中删除所有空格,例如 prices[0] = '2673.00'

prices = ['2 673.00', '53.55', '1 478.00', ... ]
prices = [float(x) for x in prices]

我尝试了各种选择,但没有一个对我有用。

x = str(prices[0]).replace(' ', '') # Got error --> ValueError: could not convert string to float: '2\xa0673.00'

import unicodedata
my_str = unicodedata.normalize("NFD", str(prices[0])) # tried  ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’ as different forms but got same error as above

x = str(prices[0]).replace(u'\xa0', u'')  # Got error --> ValueError: could not convert string to float: '2\xa0673.00'

请提出一种可能的方法。谢谢。

【问题讨论】:

  • 您可以使用像re.compile(r'\s+', re.U) 这样的正则表达式删除任何空格。

标签: python regex string replace


【解决方案1】:

如果给出输入,这肯定会起作用:

import re
regexp = re.compile(r'\s+', re.UNICODE)
prices_norm = [regexp.sub('', p) for p in prices]

但更好的解决方案是不要打印带有空格的浮点数。只需在打印之前更改locale

import locale
locale.setlocale(locale.LC_ALL, 'en_US')

【讨论】:

    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多