代码只运行一个单词,而不是整个字符串
def silly_case(in_string):
firstlet = in_string[0]
firstlet = firstlet.lower()
upperpart = in_string[1:]
upperpart = upperpart.upper()
in_string = firstlet + upperpart
return in_string
silly_string = silly_case("This is a string")
print(silly_string)
答案 0 :(得分:5)
您可以使用内置功能title
和swapcase
:
>>> "This is a string".title().swapcase()
'tHIS iS a sTRING'
要修复代码,您应该将字符串拆分成多个单词,然后遍历它们,然后再对每个单词应用大小写逻辑:
def silly_case(in_string):
words = []
for word in in_string.split():
firstlet = word[0]
firstlet = firstlet.lower()
upperpart = word[1:]
upperpart = upperpart.upper()
words.append(firstlet + upperpart)
return ' '.join(words)
silly_string = silly_case("This is a string")
print(silly_string)