声明无效(Python)

时间:2017-08-30 03:59:45

标签: python-3.x

程序从一个给定的字符串中获取一个字符串,其中所有出现的第一个字符都已更改为' $',除了第一个字符本身。 示例字符串:'重启' 预期结果:' resta $ t'

这是我的代码

    def change(string):
        string_len = len(string)
        t = string[0]
        for each in range(1, string_len):
            if each is t:
                each == '$'
            else:
                continue
    return string

print(change("restart"))

output
restart

我使用Pycharm。第6行(每个==' $')表示此声明无效。我不想使用替换方法。只想知道是什么问题。

2 个答案:

答案 0 :(得分:1)

您的代码已评论:

    def change(string):
        string_len = len(string)
        t = string[0]
        for each in range(1, string_len):
            if each is t: # To compara strings you should use the == operator not the 'is' operator.
                each == '$' # This will not have any effect because is a temporal variable visible just inside the 'for' loop and you are not using it.
            else:
                continue
    return string

print(change("restart"))

解决方案可能是:

def change(s):
    result = ''
    for character in s:
        result += '$' if character == s[0] else character
    return result


print(change('restart'))

Python字符串是不可变对象,因此您无法'aaa'[1] = 'b'获取aba

答案 1 :(得分:0)

each设置为整数,您将其与字符串进行比较。