获取一个python切片来反转一部分字符串的顺序(交换一个字符串中的连续字符)?

时间:2014-09-21 03:14:29

标签: python

鉴于"珊瑚"这个词,我需要它给我每个字母对的逆转。例如:

ocral
croal
coarl
corla

我得到了什么:

string  = raw_input("Enter a word:")
char_values = len(string) #length of string
char_values = int(char_values) #converts to number
print "DELETIONS:"
for word_value in range(char_values): 
print string[:word_value] + string[word_value+1:] #deletion pattern
print "TRANSPOSITIONS:"
for x in range(char_values):
print string[:x:-1]+string[x+2:] #shift pattern

我在最后一行中抛出猜测。我的结果是laroral laral lal l

2 个答案:

答案 0 :(得分:4)

这应该适合你:

#!/usr/bin/env python

wrd = raw_input('Enter a word: ')

for i in range(len(wrd) - 1):
    print wrd[0:i] + wrd[i+1] + wrd[i] + wrd[i+2:]

输出:

paul@local:~/Documents/src/sandbox$ ./rev.py
Enter a word: coral
ocral
croal
coarl
corla
paul@local:~/Documents/src/sandbox$ 

答案 1 :(得分:1)

交换字符

string  = "apple"
char_values = len(string) #length of string
char_values = int(char_values) #converts to number
index  = 0
for word_value in range(char_values): 
    firstcharacter = string[word_value]
    others = string[:word_value] + string[word_value+1:]
    if index+1 < char_values:
        nextCharacter = string[index+1]
        print others[:index] + nextCharacter + firstcharacter+ others[index+1:]
    index = index +1

输出:

ocral
croal
coarl
corla