I have a list containing floating numbers (positive or negative) which are separated by a hyphen. I would like to split them.
For example:
input: -76.833-106.954, -76.833--108.954
output: -76.833,106.954,-76.833,-108.954
I've tried re.split(r"([-+]?\\d*\\.)-"
, but it doesn't work. I get an invalid literal statement for int()
Please let me know what code would you recommend me to use. Thank you!
Completing @PyHunterMan's answer:
You want only one hyphen to be optional before the number indicating a negative float:
import re
target = '-76.833-106.954, -76.833--108.954, 83.4, -92, 76.833-106.954, 76.833--108.954'
pattern = r'(-?\d+\.\d+)' # Find all float patterns with an and only one optional hypen at the beggining (others are ignored)
match = re.findall(pattern, target)
numbers = [float(item) for item in match]
print(numbers)
>>> [-76.833, -106.954, -76.833, -108.954, 83.4, 76.833, -106.954, 76.833, -108.954]
You will notice this does not catch -92
and besides -92
is part the Real numbers set, is not written in float format.
If you want to catch the -92
which is an integer use:
import re
input_ = '-76.833-106.954, -76.833--108.954, 83.4, -92, 76.833-106.954, 76.833--108.954'
pattern = r'(-?\d+(\.\d+)?)'
match = re.findall(pattern, input_)
print(match)
result = [float(item[0]) for item in match]
print(result)
>>> [-76.833, -106.954, -76.833, -108.954, 83.4, -92.0, 76.833, -106.954, 76.833, -108.954]
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.