这是我的代码:
def cap_space(txt):
e = txt
upper = "WLMFSC"
letters = [each for each in e if each in upper]
a = ''.join(letters)
b = a.lower()
c = txt.replace(a,' '+b)
return c
我为找到给定字符串上的大写字母而将其替换为空格和后者的小写字母的人
输入示例:
print(cap_space('helloWorld!'))
print(cap_space('iLoveMyFriend'))
print(cap_space('iLikeSwimming'))
print(cap_space('takeCare'))
输出应该是什么样的:
hello world!
i love my friend
take care
i like swimming
我得到的输出是:
hello world!
iLoveMyFriend
iLikeSwimming
take care
这里的问题是,由于某种原因,仅在给定字符串中仅存在一个大写字母的情况下才应用该条件,我如何改进它以使其应用于给定字符串上的每个大写字母?
您可以使用一些不错的python3
方法str.translate
和str.maketrans
:
In [281]: def cap_space(txt):
...: upper = "WLMFSC"
...: letters = [each for each in txt if each in upper]
...: d = {i: ' ' + i.lower() for i in letters}
...: return txt.translate(str.maketrans(d))
...:
...:
In [283]: print(cap_space('helloWorld!'))
...: print(cap_space('iLoveMyFriend'))
...: print(cap_space('iLikeSwimming'))
...: print(cap_space('takeCare'))
hello world!
i love my friend
i like swimming
take care
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句