[英]How exactly does Python's .replace() works?
我試圖替換兩個不同的字符@
和.
在一個字符的字符串中|
. 當我將替換變量分配給同一個變量時, @
和.
到|
有效,但使用不同的變量,它只會將點替換為|
. 我可以知道造成差異的原因是什么嗎?
使用相同的變量:
email = input("Please enter your email address : ")
for x in ('@','.'):
email = email.replace(x,'|')
print(email)
Output:
Please enter your email address : sdf@sadfs.com
sdf|sadfs|com
使用其他變量:
email = input("Please enter your email address : ")
for x in ('@','.'):
temp_email = email.replace(x,'|')
print(temp_email)
Output:
Please enter your email address : sdf@sadfs.com
sdf@sadfs|com
在第一個循環中,當循環執行時,您將兩次覆蓋email
email = email.replace(x,'|')
在第二個循環中,將其存儲在temp_email
中,因此email
不會被覆蓋。 當我們執行
temp_email = email.replace(x,'|')
第一次, x='@'
,所以temp_email
變為sdf|sadfs.com
。 然后第二次執行, x='.'
,所以temp_email
變為sdf@sadfs|com
。 這是因為它兩次都在編輯email
來創建temp_email
,但是email
沒有改變!
在你的 (for) 循環的第一次執行將把 @ 變成 '|' Temp_email = sdf@sadfs.com
但是 email 沒有改變
所以 email = sdf@sadfs.com
在您的 (for) 循環的第二次執行時將輪流。 到“|”
然后
Temp_email = sdf@sadfs|com
然后它打印
這是您的預期代碼
<script src="//onlinegdb.com/embed/js/i-fTLYV9M?theme=dark"></script>
請給兄弟投票
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.