简体   繁体   English

Python's.replace() 究竟是如何工作的?

[英]How exactly does Python's .replace() works?

I was trying to replace two different characters @ and .我试图替换两个不同的字符@. in a string with one character |在一个字符的字符串中| . . When I assign the replacing variable to the same variable, the replacing of @ and .当我将替换变量分配给同一个变量时, @. to || works, but using different variable, it only replace dot to |有效,但使用不同的变量,它只会将点替换为| . . May I know what's the reason causing the difference?我可以知道造成差异的原因是什么吗?

Using same variable:使用相同的变量:

email = input("Please enter your email address : ")
for x in ('@','.'):
     email = email.replace(x,'|')
print(email)

Output: Output:

Please enter your email address : sdf@sadfs.com
sdf|sadfs|com

Using other variable:使用其他变量:

email = input("Please enter your email address : ")
for x in ('@','.'):
     temp_email = email.replace(x,'|')
print(temp_email)

Output: Output:

Please enter your email address : sdf@sadfs.com
sdf@sadfs|com

In the first loop, you're overwriting email both times, when the loop executes在第一个循环中,当循环执行时,您将两次覆盖email

email = email.replace(x,'|')

In the second loop, you store it in temp_email , so email isn't overwritten.在第二个循环中,将其存储在temp_email中,因此email不会被覆盖。 When we execute当我们执行

temp_email = email.replace(x,'|')

the first time, x='@' , so temp_email becomes sdf|sadfs.com .第一次, x='@' ,所以temp_email变为sdf|sadfs.com Then the second time it's executes, x='.'然后第二次执行, x='.' , so temp_email becomes sdf@sadfs|com . ,所以temp_email变为sdf@sadfs|com This is because both times it's editing email to create temp_email , but email hasn't been changed!这是因为它两次都在编辑email来创建temp_email ,但是email没有改变!

At first execution of your (for) loop will turns @ to '|'在你的 (for) 循环的第一次执行将把 @ 变成 '|' Temp_email = sdf@sadfs.com Temp_email = sdf@sadfs.com

But email is un changed但是 email 没有改变

so email = sdf@sadfs.com所以 email = sdf@sadfs.com

At second execution of your (for) loop will turns.在您的 (for) 循环的第二次执行时将轮流。 to '|'到“|”

Then然后

Temp_email = sdf@sadfs|com Temp_email = sdf@sadfs|com

Then it prints然后它打印

Here is your Expected Code这是您的预期代码

 <script src="//onlinegdb.com/embed/js/i-fTLYV9M?theme=dark"></script>

Please vote up bro请给兄弟投票

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

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