Home > Software engineering >  how to compare strings in python with "\r" and "\n"
how to compare strings in python with "\r" and "\n"

Time:05-13

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Try this before you compare them:

str2 = str2.replace("\r", " ").replace("\n", " ")

CodePudding user response:

You can maybe use replace('\r',' ') and replace('\n',' ') before u compare them

  • Related