Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 字符串中每隔一个字母大写_Python_String_Python 3.x_Function - Fatal编程技术网

Python 字符串中每隔一个字母大写

Python 字符串中每隔一个字母大写,python,string,python-3.x,function,Python,String,Python 3.x,Function,这是我的代码: 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"))

这是我的代码:

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"))
输出:

AbCd EfGh IjKl
但它必须是这样的:

AbCd eFgH IjKl

我不知道我做错了什么,也不知道我应该做什么来修复它。

你可以用一个简单的理解和加入:

输出:

AbCd eFgH IjKl

注意,这并不在技术上大写每一个字母,除非你认为空格是字母,而是用其他的索引来计算,这似乎是你想要的输出所需的。 要修复当前代码,只需替换:

if char != ' ':
    i = not i
与:


您可以使用简单的理解和连接:

输出:

AbCd eFgH IjKl

注意,这并不在技术上大写每一个字母,除非你认为空格是字母,而是用其他的索引来计算,这似乎是你想要的输出所需的。 要修复当前代码,只需替换:

if char != ' ':
    i = not i
与:

产出:

AbCd eFgH IjKl
预期的输出不关心空间

产出:

AbCd eFgH IjKl

预期的输出不关心空格,因为有一个if检查,它阻止了他想做的事情if char!='':@MegaIng看起来她只是误解了空格,我不认为这是OP没有写的。看起来这是关于。在这种情况下,OP应该提供带有多个空格的示例,或者其他非字母字符,如abc de'fg..h,这将导致abc de'fg。。H@RyanHaining因为有一个if检查阻止了他想做的事情if char!='':@MegaIng看起来她只是误解了空格,我不认为这是OP没有写的。看起来这是关于。在这种情况下,OP应该提供带有多个空格的示例,或者其他非字母字符,如abc de'fg..h,这将导致abc de'fg..h