Python 3.4帮助 - 使用切片来替换字符串中的字符

时间:2014-12-04 02:01:47

标签: python-3.4

说我有一个字符串。

"poop"

我想将"poop"更改为"peep"

事实上,我也希望所有的大便中的所有人都能改变我所写的任何单词。

我试图做到这一点。

def getword():
    x = (input("Please enter a word."))
    return x
def main():
    y = getword()
    for i in range (len(y)):
        if y[i] == "o":
            y = y[:i] + "e"
    print (y)

main()  

正如您所看到的,当您运行它时,它并不等于我想要的。这是我的预期输出。

Enter a word. 
>>> brother
brether

像这样的东西。我需要使用切片来完成它。我只是不知道如何。

请保持答案简单,因为我对Python有点新鲜。谢谢!

3 个答案:

答案 0 :(得分:2)

这使用切片(但请记住,切片不是最好的方法):

def f(s):
    for x in range(len(s)):
        if s[x] == 'o':
            s = s[:x]+'e'+s[x+1:]
    return s

答案 1 :(得分:1)

python中的字符串是不可变的,这意味着你不能只换掉字符串中的字母,你需要创建一个全新的字符串并逐个连接字母

def getword():
    x = (input("Please enter a word."))
    return x

def main():
    y = getword()
    output = ''
    for i in range(len(y)):
        if y[i] == "o":
            output = output + 'e'
        else:
            output = output + y[i]
    print(output)

main()

我会帮助你一次,但你应该知道堆栈溢出不是一个家庭作业帮助网站。你应该自己解决这些问题,以获得完整的教育经验。

修改

使用切片,我想你可以这样做:

def getword():
        x = (input("Please enter a word."))
        return x

def main():
    y = getword()
    output = ''                                       # String variable to hold the output string. Starts empty
    slice_start = 0                                   # Keeps track of what we have already added to the output. Starts at 0
    for i in range(len(y) - 1):                       # Scan through all but the last character
        if y[i] == "o":                               # If character is 'o'
            output = output + y[slice_start:i] + 'e'  # then add all the previous characters to the output string, and an e character to replace the o
            slice_start = i + 1                       # Increment the index to start the slice at to be the letter immediately after the 'o'
    output = output + y[slice_start:-1]               # Add the rest of the characters to output string from the last occurrence of an 'o' to the end of the string
    if y[-1] == 'o':                                  # We still haven't checked the last character, so check if its an 'o'
        output = output + 'e'                         # If it is, add an 'e' instead to output
    else:
        output = output + y[-1]                       # Otherwise just add the character as-is
    print(output)

main()

评论应该解释发生了什么。我不确定这是否是最有效或最好的方法(这真的无关紧要,因为切片是一种非常低效的方式来做到这一点),只是我一起攻击使用切片的第一件事。 / p>

编辑是的... Ourous的解决方案更加优雅

答案 2 :(得分:0)

甚至可以在这种情况下使用切片吗?

正如MirekE所说,我认为唯一可行的解​​决办法是y.replace("o","e")