martedì 5 giugno 2018

Python: Convert string to number/float

# consigliato
import re
a="PL Km 274+169 (Privato)" 
valore = str(re.sub("[^0-9,+]", "",a)).replace('+','.').replace(',','.')
print valore

result:
274.169

import string
a="PL Km 274+169 (Privato)" 
all=string.maketrans('+','.')
nodigs=all.translate(all, string.digits)
print  str(float(a.translate(all, nodigs)))

import re
a="PL Km 274+169 (Privato)" 
a.replace("+",".")
value = float(re.sub("[^0123456789\.]","",a))
print value

# consigliato
import re
def converti(a):
 valore = str(re.sub("[^0-9,+]", "",a)).replace('+','.')
 return float(valore)

import string
a="PL Km 274+169 (Privato)" 
all=string.maketrans('+','.')
nodigs=all.translate(all, string.digits)
print  str(float(a.translate(all, nodigs)))

result:
274.169

Nessun commento: