简体   繁体   English

将字符串中的每个其他字母大写

[英]capitalize every other letter in a string

This is my code: 这是我的代码:

def mock(s):
    ret = ""
    i = True  
    for char in s:
        if i:
            ret += char.upper()
        else:
            ret += char.lower()
        if char != ' ':
            i = not i
    return ret
print(mock("abcd efgh ijkl"))

output: 输出:

AbCd EfGh IjKl

but it has to be like this: 但必须是这样的:

AbCd eFgH IjKl

I don't get what i'm doing wrong and what I should do to fix it. 我没有发现我做错了什么以及应该如何解决。

You could use a simple comprehension and join() : 您可以使用一个简单的comprehension和join()

s = 'abcd efgh ijkl'
morph = ''.join([e.upper() if i%2==0 else e for i, e in enumerate(s)])
print(morph)

Output: 输出:

AbCd eFgH IjKl

Note that this does not technically capitalize every other letter (unless you consider spaces to be letters), but instead capitalizes every other index, which it seems is what you want based on your desired output. 请注意,从技术上讲 ,这不会大写其他所有字母(除非您将空格视为字母),而是大写其他所有索引,这似乎是根据所需输出想要的。

To fix your current code, all you would need to do is replace: 要修复当前代码,您需要做的就是替换:

if char != ' ':
    i = not i

With: 带有:

i = not i
def mock(s):
    ret = ""
    i = True  
    for char in s:
        if i:
            ret += char.upper()
        else:
            ret += char.lower()

        i = not i

    return ret
print(mock("abcd efgh ijkl"))

Outputs: 输出:

AbCd eFgH IjKl

The expected output does not care about spaces 预期输出不关心空格

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

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