在字符串处查找字符的索引

2024-09-26 17:42:51 发布

您现在位置:Python中文网/ 问答频道 /正文

该代码为每个偶数打印大写的字符串。 我用索引计数器(index=0)检查每个字符的索引。 有没有其他方法可以找到索引?没有肌酸指数?你知道吗

def myfunc(str):
    index = 0
    low = str.lower()
    new_str = ''
    for char in str:
        if index % 2 == 0:
            new_str += char.upper()
        else:
            new_str += char
        index += 1
    return new_str

print(myfunc('Hello World'))

Tags: 方法字符串代码newindexdef计数器指数
3条回答

尝试使用:

from itertools import zip_longest
def myfunc(s):
    return ''.join(map(''.join, zip_longest(s[::2].upper(), s[1::2], fillvalue='')))

print(myfunc('Hello World'))

输出:

HeLlO WoRlD
def myfunc(str_string):  #  Dont use the str, its a keyword
    str_string = str_string.lower()
    new_str = ''
    for index in range(len(str_string)):  # loop through the string length rather string itself
        if index % 2 == 0:
            new_str += str_string[index].upper()
        else:
            new_str += str_string[index]
        index += 1
    return new_str

print(myfunc('Hello World'))


# one liner
str_index = 'Hello World'
print("".join([str_index[i].upper() if i%2==0 else str_index[i].lower() for i in range(len(str_index))  ]))

使用Enumerate()方法向iterable添加一个计数器,并以枚举对象的形式返回它。你知道吗

例如

def myfunc(str):
    new_str = ''
    for index,char in enumerate(str):
        if index % 2 == 0:
            new_str += char.upper()
        else:
            new_str += char
    return new_str

print(myfunc('Hello World'))

O/p:

HeLlO WoRlD

相关问题 更多 >

    热门问题