python的逆序

2024-09-29 23:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我坚持做以下实验练习:

The first piece we need is a routine that, given a word, will in someway jumble up the order of all but the first and the last characters. Rather than just randomly moving the characters around we will reverse the order of the letters. The following code achieves this:

def jumble(x):
    return x[len(x)::-1]
my_string="Alistair"
print(" Reverse ",jumble(my_string))

Copy the above code to a file and run it. Currently it reverses the order of all the characters in "my_string". Modify the code so that the first and last letters of the word are NOT reversed. That is, instead of producing "riatsilA" it produces "Aiatsilr".

这是我对上述部分的代码:

def jumble(x):
    temp0=x[0]
    temp_last=x[-1]
    x_new=temp0 + x[-2:0:-1] + temp_last
    return x_new
my_string="Alistair"
print(" Reverse ",jumble(my_string))

The above routine does not account for leading or trailing white space, punctuation or other characters that might legitimately be part of the character string, but that should not be jumbled up. For example if the string were " Alistair, " the result should be " riatsilA, ". Modify your routine so that only the FIRST contiguous series of alphabetical characters (minus the first and last characters) are reversed. Ensure that the final returned string includes all other leading and trailing characters.

我不知道该怎么做,因为空格和标点符号可以在任何地方出现,我想有两个列表,一个是空白和标点,另一个是“连续的字母字符序列”,使用append方法在每个列表中追加元素,但不确定如何保存索引。Can有人帮我吗?提前谢谢。在


Tags: andofthestringthatmycodeorder
2条回答
#!/usr/bin/env python
#-*-coding:utf-8-*-
import re

def reverse(s):
    p = re.compile(r'\w+')
    for m in p.finditer(s):
        word = m.group()
        if word:
            p = s.partition(word)
            l = list(p)
            index = p.index(word)
            l[index] = l[index][::-1]
            l2 = list(l[index])
            l2[0],l2[-1]=l2[-1],l2[0]
            l[index]=''.join(l2)
            s = ''.join(l)
    return s

s="Alistair Chris,"
print reverse(s)

修好了。在

下面的代码片段可以帮助您完成最后一个任务。 如果在字符串的开始或结尾之外的其他地方发现了特殊字符,则对于子集的恢复没有特殊处理。在

# Special chars which should be ignored for reverting
SPECIALCHARS = [' ', '.', ',']

def reverse( string_ ):
    # Find occurence of 'special' chars. Stack position and char into a list.
    specchar = [( i, ltr ) for i, ltr in enumerate( string_ ) if ltr in SPECIALCHARS]
    if specchar:
        # Remove all the special characters
        newstring = ''.join( c for c in string_ if c not in SPECIALCHARS )
        # Reverse the legal characters
        newstring = newstring[::-1]
        offset = 0
        # Re-insert the removed special chars
        for pos, char in specchar:
            if pos + 1 + offset >= len( newstring ):
                # Append at the end
                newstring += char
            else:
                # Insert
                newstring = newstring[:pos + offset] + char + newstring[pos + offset:]
                offset += 1
        return newstring
    else:  # No special char at all, so just revert
        return string_[::-1]


print " '%s' =?= ' riatsilA, '" % ( reverse( " Alistair, " ) )

将导致以下输出:' riatsilA, ' =?= ' riatsilA, '

只需返回忽略第一个和最后一个字符是一行代码。 用这个来反转“中间”:t[1:-1][::-1] 然后添加第一个和最后一个字符。在

^{pr2}$

编辑

好吧,现在我想我明白你想要什么了:-)

newstr = ""
fullstr = ""
for char in mystr:
    if char in SPECIALCHARS:
        if len( newstr ): # Is already something to invert there?
            #Ignore 1st and last char and revert the rest
            newstr = newstr[0] + newstr[1:-1][::-1] + newstr[-1]
            fullstr += newstr + char
        else: # Special char found but nothing to revert so far
            fullstr += char
        newstr = ""
    else: # No special char so just append
        newstr += char
print "'%s'" % fullstr

相关问题 更多 >

    热门问题