此处,字符串flight_details
的字符串已更改,但其ID不变,以下是代码及其输出:
import re
flight_details = "Flight Savana Airlines a2134"
print(id(flight_details))
print(re.sub(r"Flight", r"Plane", flight_details))
print(id(flight_details))
print(re.sub(r"Plane", r"Akash", flight_details))
print(id(flight_details))
输出:
27264016
Plane Savana Airlines a2134
27264016
Flight Savana Airlines a2134
27264016
答案 0 :(得分:2)
id(flight_details)
在调用re.sub
之后返回相同的值,因为
re.sub
不会更改传递给它的字符串(flight_details
)的值。它返回一个新字符串。
例如:
import re
flight_details = "Flight Savana Airlines a2134"
print(flight_details)
print(id(flight_details))
re.sub(r"Flight", r"Plane", flight_details)
print(flight_details)
print(id(flight_details))
flight_details = re.sub(r"Flight", r"Plane", flight_details)
print(flight_details)
print(id(flight_details))
输出:
Flight Savana Airlines a2134
1442959741216
Flight Savana Airlines a2134
1442959741216
Plane Savana Airlines a2134
1442959741456