python字符串是不可变的,但“ re.sub()”可以对其进行突变吗?

时间:2019-06-20 09:59:07

标签: python-3.x string object immutability id

此处,字符串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

1 个答案:

答案 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

请参阅:https://docs.python.org/3/library/re.html#re.sub