首页 > 解决方案 > 如何在字符串中交替更改大写和小写?

问题描述

我想从给定的字符串创建一个新的字符串,大写和小写交替。

我尝试遍历字符串并首先将大写更改为新字符串,然后再次将小写更改为另一个新字符串。

def myfunc(x):
    even = x.upper()
    lst = list(even)
    for itemno in lst:
        if (itemno % 2) !=0:
            even1=lst[1::2].lowercase()
        itemno=itemno+1   
    even2=str(even1)
    print(even2)

由于我无法更改给定的字符串,因此我需要一种创建新字符串备用大写字母的好方法。

标签: pythonpython-3.x

解决方案


这里有一个在线人

"".join([x.upper() if i%2 else x.lower() for i,x in enumerate(mystring)])

推荐阅读