首页 > 解决方案 > 在没有替换功能的情况下替换python中的字符

问题描述

def replace_characters(the_string):

    new_string = ''

    for i in range(len(the_string)-1):

        slice_string = the_string[i: i + 2]

        if slice_string == 'ph':
            new_string += 'b

        else:
            new_string = the_string

    print(new_string)

if __name__ == "__main__":
    the_string = input('What string do you want to process?')
    replace_characters(the_string)

对于输出,如果我有 ph 的输入,我可以得到 φ,但当字符串较长时(比如电话)就不行了。我想得到 φone

标签: python

解决方案


我看到三个问题

(1)else替换所有字符串,但应添加一个字符,如new_string += the_string[i].

(2) 使用for-loop 不能跳过第二个字符ph,它可以h与下一个字符一起使用,或者将其添加到新字符串中。如果你有 statemant 的变化,ho那么它会phoph+ho

(3) 使用len(the_string)-1它可能会跳过最后一个字符。

我的版本

def replace_characters(the_string):

    new_string = ''

    i = 0
    while i < len(the_string):

        slice_string = the_string[i: i+2]

        if slice_string == 'ph':
            new_string += '\u03d5'
            i += 2  

        elif slice_string == 'th':
            new_string += '\u03b8'
            i += 2 

        elif slice_string == 'ch':
            new_string += '\u03c7'
            i += 2

        else:
            new_string += the_string[i]
            i += 1

    print(new_string)

if __name__ == "__main__":
    the_string = 'phone'
    replace_characters(the_string)

推荐阅读