Home > Net >  How to seperate decimal numbers written back to back
How to seperate decimal numbers written back to back

Time:10-27

How would it be possible to seperate a string of values (in my case, only corresponding to roman numeral values) into elements of a list?

'10010010010100511' -> [100, 100, 100, 10, 100, 5, 1, 1,]

I wanted to work with zeros on this but my idea wouldn't work with V and I's.

CodePudding user response:

You were on the right track with zeros, you have to notice that every base roman numeral is either a 1 or 5 followed by some amount of zeros. You can represent that as a very simple regex.

import re

s = '10010010010100511'

pattern = "[1|5]0*"

matches = re.finditer(pattern=pattern, string=s)

l = [match[0] for match in matches]

print(l) # ['100', '100', '100', '10', '100', '5', '1', '1']

If for some reason you don't want to use regex, you can simply iterate over each character using the same principle:

string = '10010010010100511'

lst = []
for char in string:
    if char in ['1', '5']:
        lst.append(char)
    elif char == '0':
        lst[-1]  = '0'

print(lst) # ['100', '100', '100', '10', '100', '5', '1', '1']

CodePudding user response:

Code:

s='10010010010100511'
d=[]
c=0                               #introducing this new varible just to know from where 
for i in range(len(s)):           ##Here basic idea is to check next value
    if i 1 <len(s):  
        if s[i 1]!='0':           #if NEXT value is not zero thn
            d.append(s[c:i 1])    #get string from - to and add in d list
            c=len(s[:i 1])        
    else:
        d.append(s[-1])
d

Output:

['100', '100', '100', '10', '100', '5', '1', '1']
  • Related