I have 2 strings
str1 = "SWITCH ASSY Drawing No.: NA "
str2 = "SWITCH ASSY\r\nDrawing No.: NA\r\n"
Python evaluates str1 == str2
as False
and it is pretty obvious why.
What can I do to str1 so that the "\r" and "\n" are ignored and str1 == str2
becomes True
?
Suppose I can only manipulate str1. Is it even possible?
Do a regex replacement on all whitespace characters, and replace them with single spaces:
str1 = "SWITCH ASSY Drawing No.: NA "
str2 = "SWITCH ASSY\r\nDrawing No.: NA\r\n"
if re.sub(r'\s', ' ', str1) == re.sub(r'\s', ' ', str2):
print("EQUAL") # prints EQUAL
您可以在比较它们之前使用 replace('\r',' ') 和 replace('\n',' ')
Simple replace two spaces with \r\n
str1 = str1.replace(" ","\r\n")
Test code
str1 = "SWITCH ASSY Drawing No.: NA "
str2 = "SWITCH ASSY\r\nDrawing No.: NA\r\n"
str1 = str1.replace(" ", "\r\n")
print(str2 == str1)
# Output
# True
在比较它们之前试试这个:
str2 = str2.replace("\r", " ").replace("\n", " ")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.