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
總結
以上是生活随笔為你收集整理的python语言逆序符号_python的逆序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 检查记录存在_Mysql 插
- 下一篇: python123测验7程序题答案_Py