python - 如何使枚举不计算空白的索引?

标签 python python-3.x

我正在尝试编写一个函数,它将接受一个句子并使每个奇数字母变为大写字母,每个偶数字母变为小写字母。

这是我尝试过的:

def func(st):
    res = []
    for index, c in enumerate(st):
        if index % 2 == 0:
            res.append(c.upper())
        else:
            res.append(c.lower())
    return ''.join(res)
print(myfunc(something))

当输入为 "Hello my Guy" 时,输出为 "HeLlO My gUy" 而不是 "HeLlO mY gUy" 因为它算作一个字母空白,我该怎么办?

最佳答案

我会这样写:

from itertools import cycle

def my_func(st):
    operation = cycle((str.upper, str.lower))
    conv = [next(operation)(c) if c != ' ' else c for c in st]
    return ''.join(conv)

演示:

>>> my_func("Hello my guy")
'HeLlO mY gUy'

关于python - 如何使枚举不计算空白的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72741198/

相关文章:

python - 权限被拒绝在 linux 中使用 shebang 行运行 python 脚本

Python Pandas - 在以下单元格为空白的列中填写文本值

python - 从 Redis 中的 channel 弹出消息

python-3.x - Python 3.7 非阻塞请求?

python - python 正则表达式和选择列的建议

python - 为什么我的 Python MySQLdb 脚本可以查看我的数据库,但不能对其进行实时更改?

python - 基于列表替换 pandas df 中的值的最佳方法

python-3.x - 从 Azure Blob 存储、Flask Python、HTML/JS 检索并显示?

python - Pyautogui 命令的热键是什么?

python - 将图像旋转 90 度