Currently I am having this kind of a list:
['Rating 3.9577555469954', 'Rating 3.730694980695', 'Rating 4.0717869548437', 'Rating 4.0597014925373', 'Rating 3.7323798994975']
I am trying to get rid of the 'Rating ' part. How do I achieve that in the end there are only numbers/floats in my list?
An alternative to jordanm's answer using regex
:
import re
strings = ['Rating 3.9577555469954', 'Rating 3.730694980695', 'Rating 4.0717869548437', 'Rating 4.0597014925373', 'Rating 3.7323798994975']
floats = [float(re.findall('([0-9]+[,.]+[0-9]+)',x)[0]) for x in strings]
print(floats)
Outputs:
[3.9577555469954, 3.730694980695, 4.0717869548437, 4.0597014925373, 3.7323798994975]
This will capture all digits, regardless of "Rating" or other word that might precede it. (in case there's Ratings
for example)
Loop through list and strip the value. I like to use UPPER or LOWER to catch all cases.
my_list = ['Rating 3.9577555469954', 'Rating 3.730694980695',
'Rating 4.0717869548437', 'Rating 4.0597014925373', 'Rating 3.7323798994975']
new_list = []
for value in my_list:
new_list.append(value.upper().strip('RATING').strip())
print(new_list)
Results:
['3.9577555469954', '3.730694980695', '4.0717869548437', '4.0597014925373', '3.7323798994975']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.