skybreaker
skybreaker

Reputation: 273

How does one talk about comparing positions of characters in a string?

For example, let's say I've assigned integer values to A, B, and C, like so:

def values(char):
    if char == 'A':
        val = 1
    if char == 'B':
        val = 2
    if char == 'C':
        val = 3
    return value

Now I have another function that is used to give me the value of a string with the characters A, B, and C. If the character is less than the character to its left, the total value would decrease. Otherwise, the value would continue to increase.

I had a for loop:

for c in abcstring[1:]:
   if values(c) < values(c-1)

But then it didn't work and I remembered it's because c is still a letter from the string, and you can't subtract 1 from a letter. How, then, do I specify that I want the value of the character to the left of c?

Upvotes: 1

Views: 76

Answers (2)

Others
Others

Reputation: 3023

To keep track of an index while iterating, you can use enumerate!

for index,c in enumerate(abcstring[1:]):
    if values(c) < values(abscstring[index-1]):
        ...

Or, to save you the slice, you could even use the start parameter:

for index,c in enumerate(abcstring, start=1):
    if values(c) < values(abscstring[index-1]):
        ...

Which is slightly more verbose, but perhaps more clear.

Upvotes: 3

Dan Oberlam
Dan Oberlam

Reputation: 2496

First of all, you could simplify your values function to get rid of the if statements by using a dictionary. Also, your function won't work because you're assigning val = some number but then you return value.

char_dict = {'A': 1, 'B': 2, 'C': 3}

def values(char):
    return char_dict[char]

Here are two ways to refer to the previous character. The first would be to keep track of it.

previous = abcstring[0]

for c in abcstring[1:]:
    if values(c) < values(previous):
        do_something()
    previous = c

Or you could use a range instead.

for i in range(1, len(abcstring)):
    c = abcstring[i]
    previous = abcstring[i-1]
    if values(c) < values(previous):
        do_something()

You could also use an enumeration, as pointed out in the other answer.

Upvotes: 2

Related Questions