Pete Lavelle
Pete Lavelle

Reputation: 103

python splitting string twice

I'm trying to split a string twice with the goal of converting a>b where b contains numbers and is split into multiple x/y pairs

a = '{1;5}{2;7}{3;9}{4;8}'
b = [[1,5],[2,7],[3,9],[4,8]]

my code is currently this...

b = a.split('}{')
for item in b:
    item.replace('{','')
    item.replace('}','')
    item.split(';')

the first split works correctly and returns this

b = ['{1;5','2;7','3;9','4;8}']

but manipulating the 'items in b' does not appear to work

Upvotes: 1

Views: 3086

Answers (4)

mkrieger1
mkrieger1

Reputation: 23131

This can also be done using regular expressions.

The items you are looking for inside the input string consist of

  • two numbers \d+
  • separated by a semicolon ;
  • enclosed in curly braces \{, \}.

The complete pattern looks like this:

pattern = r'\{(\d+);(\d+)\}'

The additional parentheses () define groups which allow extracting the numbers, for example with re.findall:

>>> for item in re.findall(pattern, a):
>>>     print item
('1', '5')
('2', '7')
('3', '9')
('4', '8')

Then it is a simple matter of mapping int over the items to get the desired result:

>>> [map(int, item) for item in re.findall(pattern, a)]
[[1, 5], [2, 7], [3, 9], [4, 8]]

Some prefer list comprehensions over map:

>>> [[int(x) for x in item] for item in re.findall(pattern, a)]
[[1, 5], [2, 7], [3, 9], [4, 8]]

Upvotes: 1

lapinkoira
lapinkoira

Reputation: 8978

You have to actually modify the list b by interacting with its item. You should do something like this:

for i, s in enumerate(b):
    b[i] = s.replace('{','')
    b[i] = s.replace('}','')
    b[i] = s.split(';')

In [9]: b
Out[9]: [['{1', '5'], ['2', '7'], ['3', '9'], ['4', '8}']]

I dont know if that's your expected output

Here are two examples where you are not affecting the list b

for item in b:
    item = item.replace('{','')
    item = item.replace('}','')
    item = item.split(';')

In [21]: b = ['{1;5','2;7','3;9','4;8}']

In [22]: for item in b:
        item = item.replace('{','')
        item = item.replace('}','')
        item = item.split(';')


In [23]: b
Out[23]: ['{1;5', '2;7', '3;9', '4;8}']

This one wouldnt do anything to the list b neither.

for item in b:
    item.replace('{','')
    item.replace('}','')
    item.split(';')

Upvotes: 1

Klaus D.
Klaus D.

Reputation: 14369

You can use a list comprehension to do both splits at once and return a list of lists:

>>> a = '{1;5}{2;7}{3;9}{4;8}'
>>> [item.split(';') for item in a[1:-1].split('}{')]
[['1', '5'], ['2', '7'], ['3', '9'], ['4', '8']]

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 992737

The function call

item.replace('{','')

does not do anything to item, since it returns a new string after the replacement. Instead, try:

item = item.replace('{','')

Similar changes need to be made for the other lines in that block.

Upvotes: 0

Related Questions