python语言逆序符号_python的逆序

下面的代码片段可以帮助您完成最后一个任务。

如果在字符串的开始或结尾之外的其他地方发现了特殊字符,则对于子集的恢复没有特殊处理。在# 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值