简体   繁体   English

交替添加大写和小写字母?

[英]Alternately add uppercase and lowercase letters?

I am working on a task for a beginner python course.我正在为初学者 python 课程做一项任务。 Task is to take first uppercase letter and then lowercase letter and all over again.任务是先取大写字母,然后再取小写字母,然后再一遍。

this is input string:这是输入字符串:

"ifeFemFEkej83FkW"

and this should be output string:这应该是 output 字符串:

FeFkFkW

friend and I came up with this solution, but it looks a little bit complicated, and I was wondering if there is maybe one-line solution or regular expression for some part of the code?我和朋友想出了这个解决方案,但它看起来有点复杂,我想知道代码的某些部分是否有单行解决方案或正则表达式? Or maybe some different approach to the task.或者也许是一些不同的任务方法。 Thank you for your help.谢谢您的帮助。

str_a = "ifeFemFEkej83FkW"
new = ""
upper_case = True

for i in str_a:
    if "A" < i < "Z" and upper_case == True:
        new += i
        upper_case = False
    elif "a" < i < "z" and upper_case == False:
        new += i
        upper_case = True

print(new)

Here's a way to simplify it, using the isupper() function and the fact that you can always flip a bool to its opposite with not :这是一种简化它的方法,使用isupper() function 以及您始终可以使用not将 bool 翻转到相反的事实:

str_a = "ifeFemFEkej83FkW"
new = ""
upper_case = True

for i in str_a:
    if i.isupper() == upper_case:
        new += i
        upper_case = not upper_case

print(new)

And here's an approach with itertools.groupby .这是使用itertools.groupby的方法。 This would be a pretty clean one-liner if not for the requirement of dropping initial lowercase letters:如果不要求删除初始小写字母,这将是一个非常干净的单行:

import itertools

str_a = "ifeFemFEkej83FkW"

new = ''.join(next(g) for _, g in itertools.groupby(str_a, str.isupper))
new = new if new[0].isupper() else new[1:]

print(new)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM