Python 小写和大写字符串
Python Lowercase and Uppercase String
有没有办法将字符串转换为大小写字母序列?
例如,"Kilometers" → "KiLoMeTeRs".
a = 'Kilometers'
print(''.join([char.upper() if i%2==0 else char.lower() for i, char in enumerate(a)]))
结果 = 'KiLoMeTeRs'
更深奥的方法:
>>> a = 'Kilometers'
>>> "".join("".join(i) for i in zip(a[::2].upper(), a[1::2].lower()))
'KiLoMeTeRs'
或使用@lenik 更简洁的形式:
>>> "".join(a+b for a, b in zip(a[::2].upper(), a[1::2].lower()))
有没有办法将字符串转换为大小写字母序列?
例如,"Kilometers" → "KiLoMeTeRs".
a = 'Kilometers'
print(''.join([char.upper() if i%2==0 else char.lower() for i, char in enumerate(a)]))
结果 = 'KiLoMeTeRs'
更深奥的方法:
>>> a = 'Kilometers'
>>> "".join("".join(i) for i in zip(a[::2].upper(), a[1::2].lower()))
'KiLoMeTeRs'
或使用@lenik 更简洁的形式:
>>> "".join(a+b for a, b in zip(a[::2].upper(), a[1::2].lower()))