Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Converting a string to an integer [duplicate]

Tags:

python

string

int

I need to convert a string from a file that I have into an integer. The string in question is just one number.

L= linecache.getline('data.txt', 1)
L=int(L)  

print L   

I receive the error:

ValueError: invalid literal for int() with base 10: '\xef\xbb\xbf3\n'

How do I convert this string into an integer?

like image 739
har.cruz1972 Avatar asked Jan 13 '23 04:01

har.cruz1972


2 Answers

The file contains an UTF-8 BOM.

>>> import codecs
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'

linecache.getline does not support encoding.

Use codecs.open:

with codecs.open('data.txt', encoding='utf-8-sig') as f:
    L = next(f)
    L = int(L)
    print L   
like image 65
falsetru Avatar answered Jan 18 '23 02:01

falsetru


Your file starts with a BOM. Strip it before trying to parse the number.

like image 35
Hyperboreus Avatar answered Jan 18 '23 01:01

Hyperboreus