在上下案件之间交替

时间:2017-10-17 19:31:10

标签: python string

我遇到了一些代码问题:

我正在尝试编码,以便在使用索引编号的情况下将句子的字母替换。

E.G:

input:hello im an idiot
output: ToIdI nA mI oLlEh

1 个答案:

答案 0 :(得分:2)

简单如下:

>>> string='hello im an idiot'
>>> out=''
>>> caps=True   #flag to see if upper case 

>>> for s in string[::-1]:        #string[::-1] reverses it
        if s==' ':                #when the char is a whitespace, directly add it to the resultant output
          out+=' '
          continue
        if caps:                 #should be uppercase
          out+=s.upper() 
          caps = False 
        else:                    #should be lowercase
          out+=s.lower() 
          caps = True 

>>> out
=> 'ToIdI nA mI oLlEh'
相关问题