简体   繁体   English

“切片”和“替换”作业的字符串

[英]"Slicing" and "Replacing" a string for homework

I am stuck on a problem for my class.我的 class 遇到了问题。 The pic of the problem is down below.问题的图片在下面。 I'm trying to convert this string "abcd efgh ijkl" to this "AbCd eFgH IjKl" using ordinal function/values to capitalize even index numbers.我正在尝试使用序数函数/值将这个字符串“abcd efgh ijkl”转换为这个“AbCd eFgH IjKl”以大写偶数索引号。

This is what I got so far:这是我到目前为止得到的:

def mock(string):
    index = 0
    for i in string:
        if string.find(i, index) % 2 == 0:
            string.replace(i,(chr(ord(i) - 32)))
        index = string.find(i) + 1
    return string

print(mock("abcd efgh ijkl"))

Any help is appreciated.任何帮助表示赞赏。

Pic of the problem问题图片

str.replace returns string, but you aren't assigning the return value to anything. str.replace返回字符串,但您没有将返回值分配给任何内容。 Also you need to handle spaces correctly (thanks @JacobStrauss for further simplification!)您还需要正确处理空格(感谢@JacobStrauss 进一步简化!)

def mock(string):
    for i in string:
        if i != ' ' and string.find(i) % 2 == 0:
            string = string.replace(i, (chr(ord(i) - 32)))
    return string

print(mock("abcd efgh ijkl"))

Prints:印刷:

AbCd eFgH IjKl

All credit to Andrej Kesely for providing a solution, but I just wanted to improve on it slightly.感谢 Andrej Kesely 提供了一个解决方案,但我只是想稍微改进一下。 Since you are already iterating over a string, and the.find() method returns an index position, you do not need to keep track of the index.由于您已经在遍历字符串,并且 .find() 方法返回索引 position,因此您不需要跟踪索引。 I've tested the code below and it works just as well.我已经测试了下面的代码,它也可以正常工作。

def mock(string):
    for i in string:
        if i != ' ' and string.find(i) % 2 == 0:
            string = string.replace(i, (chr(ord(i) - 32)))
    return string

The above returns "AbCd eFgH IjKl"以上返回“AbCd eFgH IjKl”

use a for loop and a upper the string by index character使用 for 循环和按索引字符排列字符串

def capitalize(string):
    result=""
    for i in range(len(string)):
        if i%2==0:
            result+=string[i].upper()
        else:
            result+=string[i]
    return result

string="abcd efgaah ijklaaa"
print(capitalize(string))

output: output:

AbCd eFgAaH IjKlAaA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM