1

I have a list of prices from which I want to remove all space such that the prices[0] = '2673.00'

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

I have tried various options but none has worked for me.

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'

Please suggest a possible way. Thanks.

1
  • 2
    You may remove any whitespace with a regex like re.compile(r'\s+', re.U). Commented May 16, 2017 at 13:34

1 Answer 1

3

If the input is given, this will surely work:

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

But if you have control over the production of the prices, a better solution will be not to print the floats with spaces. Just change the locale before you print them:

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.