在 Python 中将字符串中的所有其他字母大写? [英] Capitalise every other letter in a string in Python?
本文介绍了在 Python 中将字符串中的所有其他字母大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试定义一个函数,该函数将每个其他字母大写,并且还将空格包含在 accout 中,例如:
I've been trying to define a function that will capitalise every other letter and also take spaces into accout for example:
print function_name("Hello world")
应该打印 "HeLlO wOrLd" 而不是 "HeLlO WoRlD"
print function_name("Hello world")
should print "HeLlO wOrLd" rather than "HeLlO WoRlD"
我希望这是有道理的.任何帮助表示赞赏.
I hope this makes sense. Any help is appreciated.
谢谢,奥利
推荐答案
def foo(s):
ret = ""
i = True # capitalize
for char in s:
if i:
ret += char.upper()
else:
ret += char.lower()
if char != ' ':
i = not i
return ret
>>> print foo("hello world")
HeLlO wOrLd'
这篇关于在 Python 中将字符串中的所有其他字母大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文