I have this string: '51.6251.8750.6951.4651.462626200', and want to get a list like this: ['51.62', '51.87', '50.69', '51.46', '51.46', '2626200']
So, basically after find a dot, the string should be split 2 positions later.
For now, I have the following, where I created a list of all dot positions, not sure if that's the way.
import re
string = '51.6251.8750.6951.4651.462626200'
k = 2
# I couldn't find the position of the dot actually, so I had to replace for something first, it may be unecessary
subString = '-'
replacedString = re.sub('[.]', subString, string)
# create a list with all positions of the substring
subStringPosition = [i.start() for i in re.finditer(subString, replacedString)]
# add k to each element of the subStringPosition
subStringAfterK = [x + k for x in subStringPosition]
I'd appreciate if anybody can help me.
You can use the regex methods to achieve this result split and findall with the expiration of \d{2}\.\d{2} that is 2 digits followed by . and another 2 digits.
In findall it will return all the 2 numbers and 2 numbers after the . and in the split[-1] it will return the rest of the string.
string = "51.6251.8750.6951.4651.462626200"
result = re.findall(r"\d{2}\.\d{2}", string)
result.append(re.split(r"\d{2}\.\d{2}", string)[-1])
print(result)
Output
['51.62', '51.87', '50.69', '51.46', '51.46', '2626200']
You can use:
# string = '51.6251.8750.6951.4651.462626200'
matches = re.split(r'(?<=\.\d{2})', string)
Explanation:
Positive Lookbehind (?<=\.\d{2})
\. matches the character .\d{2} matches a digit exactly 2 timesResult:
#print(matches)
['51.62', '51.87', '50.69', '51.46', '51.46', '2626200']
You can test the regular expression here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With