循环中字符串的Python行为

1 python string loops

在尝试在分隔符处大写字符串时,我遇到了我不理解的行为.有人可以解释为什么字符串s在循环期间还原?谢谢.

s = 'these-three_words'  
seperators = ('-','_')  
for sep in seperators:  
    s = sep.join([i.capitalize() for i in s.split(sep)])  
    print s  
print s  

stdout:  
These-Three_words  
These-three_Words  
These-three_Words
Run Code Online (Sandbox Code Playgroud)

Pao*_*ino 6

capitalize 将第一个字符变为大写,将字符串的其余部分变为小写.

在第一次迭代中,它看起来像这样:

>>> [i.capitalize() for i in s.split('-')]
['These', 'Three_words']
Run Code Online (Sandbox Code Playgroud)

在第二次迭代中,字符串分为:

>>> [i for i in s.split('_')]
['These-Three', 'words']
Run Code Online (Sandbox Code Playgroud)

因此,在两者上运行资本化将使T为三个小写.


ber*_*nie 5

你可以使用title():

>>> s = 'these-three_words'
>>> print s.title()
These-Three_Words
Run Code Online (Sandbox Code Playgroud)