2

Very simple problem, although I am having quite a tough time solving it.

Take a look at the code and I will explain below:

def printc(some_text):
    split_text = list(some_text)

    for x in split_text:
        if x is '{'
            # this is what i need help with


printc("{CCyan, {RRed, {YYello)

The idea behind this and it is still very early in the code development, but what I am trying to do is create an iterator that searches through "split_text" and finds the character '{' then i want to test what character is situated right next to it. How would i go about doing that?

For example is searches through split_text and finds the first { i want to see if the character next to it is either A, B, C, etc...

Any ideas?

pypy
  • 160
  • 1
  • 8
  • Do you want expected the function to print `C`, `R`, and `Y` if the input is `"{CCyan, {RRed, {YYello"` ? – falsetru Aug 13 '14 at 13:42
  • 1
    Take a look at `enumerate` – user189 Aug 13 '14 at 13:43
  • 1
    also, you shouldn't be using `is` here. read up on the difference between `==` and `is`, it's important – acushner Aug 13 '14 at 13:44
  • @acushner i def will do that, i always thought it was shorthand for the same thing to make it more 'pseudo-code' – pypy Aug 13 '14 at 13:46
  • what's the real problem you are trying to solve? also, strings are already a list.. you don't need to create a list out of it. – Corley Brigman Aug 13 '14 at 13:48
  • @CorleyBrigman I find it easier to split up a string into individual characters, mess with them as I see fit and splice them back together. May not be the best way, but it works for me so far. – pypy Aug 13 '14 at 13:49
  • nope, it compares objects' identities, not their values. – acushner Aug 13 '14 at 13:49
  • @pypy, regarding a list of characters, did you know that `for x in some_text` gives the same result as `for x in list(some_text)` minus creating a completely unnecessary list? – acushner Aug 13 '14 at 17:14

3 Answers3

4

Much easier with a single regex.

import re
re.findall('{(.)', some_text)

outputs:

['C', 'R', 'Y']
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2
for x, y in zip(some_text, some_text[1:]):
    if x == '{':
        print y

you could even make it simpler:

chars = [y for (x, y) in zip(some_text, some_text[1:]) if x == '{']
acushner
  • 9,595
  • 1
  • 34
  • 34
1

I usually iterate in pairs if I need something like this:

from itertools import tee, izip

def pairwise(iterable):
    """Iterate in pairs

    >>> list(pairwise([0, 1, 2, 3]))
    [(0, 1), (1, 2), (2, 3)]
    >>> tuple(pairwise([])) == tuple(pairwise('x')) == ()
    True
    """
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

Usage is like:

for left, right in pairwise(iterable):
    ...
wim
  • 338,267
  • 99
  • 616
  • 750