[英]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.