Skip to main content
 首页 » 编程设计

循环中字符串的 Python 行为

2025年05月04日20jpfss

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

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 

请您参考如下方法:

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

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

>>> [i.capitalize() for i in s.split('-')] 
['These', 'Three_words'] 

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

>>> [i for i in s.split('_')] 
['These-Three', 'words'] 

因此,运行 capitalize on both 会将 T 变成小写。