如何在python中不替换字符串中的某些字符?

2024-09-30 22:25:33 发布

您现在位置:Python中文网/ 问答频道 /正文

假设将随机字符串中的字符(但不是最后一个“4”)替换为“!”。 或者在随机字符串中用“@”替换字符,但不替换中间的“3”

示例1:

输入(hdasd1234)

输出(!!!!!1234)

示例2:

输入(asadfe455)

输出(@@@dfe@)

x = str(input())

y = "!" * (len(x) - 4) + x[-4:]

print(x)

此代码不起作用


Tags: 字符串代码示例inputlen字符printstr
2条回答

代码正在打印未修改的x值。 您的代码逻辑正在使用结果创建一个新变量y,而x未被修改。 但是,您正在打印与输入完全相同的x值。 逻辑似乎正在运行,结果对于y的值是正确的

请检查一下。 如果有任何问题,请发布错误日志或结果

对于非常基本的直接解决方案,您可以执行以下操作:

Example one:

string = input() #input automatically returns a string, so there's no need for str()
y = '!' * (len(string)-5) + string[4:]print (y) #remember to print y, not string because y is the modified version of your string

And example two

string = input()
y = "@" * 3 + string[3:6] + "@" * 3
print (y)

对于这种方法更灵活的方法,您应该创建一个函数。假设给定了在列表中更改字符串的位置、字符串和替换string[n]的特定标记,这应该相当简单:

def replace_chars(string, positions, s):
    new_string = []
    for i in range(len(string)):
        if i not in positions: #Checking if position, i, is not one of the marked positions
            new_string.append(string[i])
        else: #If it is a marked positions, append it with the marker, s, or more specifically '@'
            new_string.append(s)
    return ''.join(new_string) #Make the list a string

这可以写在一个1-2行长的函数中,其中一行用于循环,但这种格式更便于可读性。但是如果你在1-2行中完成,它会是这样的:

def replace_chars(string, positions, s):
    new_string = [string[i] if i not in positions else s for i in range(len(string))]
    return ''.join(new_string)

相关问题 更多 >