python中的Print函数和普通字符串

2024-06-16 12:54:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是从file.txt存储的文本,它用于一些分析。从文件中读取文本后,我看到打印的变量值和存储在该变量中的实际值之间的差异

file=open("message.txt", "r")
message=file.read()
print(message)

打印输出:'MSH|^~\\&|GHH LAB|ELAB-3|GHH OE|BLDG4|200202150930||ORU^R01|CNTRL-3456|P|2.4'

上面的结果包含我的消息的打印值。现在我将打印值与message中的实际值进行比较

if message == 'MSH|^~\\&|GHH LAB|ELAB-3|GHH OE|BLDG4|200202150930||ORU^R01|CNTRL-3456|P|2.4':
        print("match found")
else:
        print("No match found")

Output: No Match found

我再次尝试使用str()和repr()方法,但返回的结果不正确


Tags: 文本txtmessagelabfileoeprintmsh
1条回答
网友
1楼 · 发布于 2024-06-16 12:54:53

您需要使用\\\\对代码中字符串文本中的反斜杠字符进行转义。 您还应该剥离()文件中提到的内容。你知道吗

以下是我的作品:

file = open("message.txt", "r")
message = file.read().strip()
print(message)
if message == 'MSH|^~\\\\&|GHH LAB|ELAB-3|GHH OE|BLDG4|200202150930||ORU^R01|CNTRL-3456|P|2.4':
        print("match found")
else:
        print("No match found")

相关问题 更多 >