练习题:字符串索引为偶数的变大写字母,返回字符串

编写一个函数,接受一个字符串,返回每个单词中偶数索引的字符大写,奇数索引的字符小写。输入字符串仅包含字母和空格,单词由单个空格分隔。

原题:Write a function  that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.

The passed in string will only consist of alphabetical characters and spaces(' '). Spaces will only be present if there are multiple words. Words will be separated by a single space(' ').

Examples:

to_weird_case('String'); # => returns 'StRiNg'

to_weird_case('Weird string case') # => returns 'WeIrD StRiNg CaSe'

我的解法:
开始思路想用x.split(' )分解字符串,后来考虑到难以拼接,故转为for循环字符串,连带空格一起处理,用i代表索引值,遇到空格归0,解决问题
def to_weird_case(string):
    i = 0
    l = []
    for x in string:
        x = x.lower()
        if x == ' ':
            l.append(x)
            i = 0
            continue
        if i % 2 == 0:
            l.append(chr(ord(x)-32))
        else:
            l.append(x)
        i += 1
    return ''.join(l)

大神解法:

def to_weird_case_word(string):
    return "".join(c.upper() if i%2 == 0 else c for i, c in enumerate(string.lower()))
    
def to_weird_case(string):
    return " ".join(to_weird_case_word(str) for str in string.split())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值