1

I have a string of data that I need to read the first two characters from, use, and then discard.

For example,

code = '2436444423'

I want to take the '24' assign it to a value 'x' and delete the '24' from the original string leaving it as:

code = '36444423'

and then assign '36' to 'y', delete it, '44' to 'z' and so on until the original string is empty.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Charles K.
  • 11
  • 1
  • 2

3 Answers3

2

You can use itertools.izip_longest (in python 3 its zip_longest ) to get the expected pairs :

>>> from itertools import izip_longest
>>> args = [iter(code)] * 2
>>> [''.join(k) for k in izip_longest(*args)]
['24', '36', '44', '44', '23']

Then you can simply assign your values to variables and use int if you want the integer type of numbers :

>>> x,y,z,j,p=[int(''.join(k)) for k in izip_longest(*args)]
>>> (x,y,z,j,p)
(24, 36, 44, 44, 23)
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    Kasra : An easy way. If the # chars are even, re.findall('..','1234567890'). If the # chars are odd re.findall('..?','123456789') – kmario23 Apr 15 '15 at 20:01
  • 1
    An alternative and very easy way: Just use, twoCharList = re.findall('..?', '123456789'). This will work whether the number of chars are either odd or even. – kmario23 Apr 15 '15 at 20:10
  • 1
    @mario23 Yes its a good solution but not for long strings! – Mazdak Apr 15 '15 at 20:11
1

Do like this:

code = '2436444423'
code = iter(code)
for x in code:
    print x, next(code)
rafaelc
  • 57,686
  • 15
  • 58
  • 82
  • I don't think this is very readable; at first blush I would never guess that this has anything to do with pairs. And `explicit is better than implicit.` – Lynn Apr 15 '15 at 19:54
  • There's no assignment. In fact, you'd be better off using zips instead of looping through a string and iterator simultaneously. – Malik Brahimi Apr 15 '15 at 20:04
0

Here's one way using a generator:

code = '2436444423'
g = (''.join(t) for t in zip(*[iter(code)]*2))
x, y = next(g), next(g)
z = next(g)

This can also be a list comprehension that evaluates to ['24', '36', '44', '44', '23'].

[''.join(t) for t in zip(*[iter(code)]*2)]

Disclaimer: this doesn't change the binding of the variable code at any point. Also if the length of code is odd, it will not return the last character.

Shashank
  • 13,713
  • 5
  • 37
  • 63
  • 1
    Shashank: Can you please consider my answer in the comment of the next answer? It works when the # chars are ODD too. – kmario23 Apr 15 '15 at 20:11
  • @mario23 I read your answer and it's good, but I don't think it would make sense in my answer. Maybe you can post an answer of your own that is focused on `re` module? – Shashank Apr 15 '15 at 20:14