简体   繁体   中英

Move index of a string in string.ascii_lowercase

I want to change letters in a string by moving the index by 2 steps: a --> c, b--> d, c--> e, etc. However, when it gets to the final letters in alphabetical order, I don't know how to make: y --> a and z --> b since it goes out of index when you reach these two letters. Also, I'm sure there's a better way to solve this problem. Thanks!

str = "rpylqjyrc"
step = 2
new_str = []

for letter in str:
    if letter in string.ascii_lowercase:
        index = string.ascii_lowercase.index(letter) + step
        word = string.ascii_lowercase[index]
        new_str.append(word)
    else:
        new_str.append(letter)

print("".join(new_str))

Here's a solution for computing a shifted character:

def shift_lc( c, shift ):
    new_ord = ord(c) + shift
    return chr( new_ord - (26 if new_ord > ord('z') else 0) )

You can use the % operator to loop through ascii_lowercase .

index = (string.ascii_lowercase.index(letter) + step) % 26

But Python already has the built-in method str.translate for these kind of string operations.

from string import ascii_lowercase as lowercases

my_string = "rpylqjyrc"

translation = str.maketrans(lowercases, lowercases[2:] + lowercases[:2])

new_string = my_string.translate(translation)

Also, I recommend you abstain from calling your variable str as this overshadows the built-in str .

This is a classic application of the modulo operator.

You want the index range between ['a', 'z'] always. There are 26 alphabets. So our new index when we add our step count has to be from [0, 26] + index of 'a' .

In order to do this, we can just do index = (index) % 26

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM