"diseases": r"(diabetes|hypertension|cancer|asthma|covid-19|stroke|"
r"alzheimer's|parkinson's|arthritis|obesity|heart disease|hepatitis|"
r"influenza|pneumonia|tuberculosis|hiv/aids|malaria|cholera|"
r"diabetes mellitus|chronic kidney disease|copd)"
为什么多个 r""
字符串之间没有 ,
,还能连在一起?
✅ 答案:Python 支持多字符串自动拼接!
在 Python 中,如果你连续写多个字符串(不管有没有加 r
),它们会 自动拼接。
例如:
s = "hello" "world"
print(s) # 输出:helloworld
即便你加上 r
,也同样成立:
s = r"hello" r"world"
print(s) # 输出:helloworld
📌 所以这段代码其实等价于:
"diseases": r"(diabetes|hypertension|cancer|asthma|covid-19|stroke|" +
r"alzheimer's|parkinson's|arthritis|obesity|heart disease|hepatitis|" +
r"influenza|pneumonia|tuberculosis|hiv/aids|malaria|cholera|" +
r"diabetes mellitus|chronic kidney disease|copd)"
但因为 Python 支持不写 +
,多个字符串自动合并,所以写成多行 r"..." r"..."
就行,不需要逗号也不需要加号。
🔍 再解释一下 r
是什么?
r
叫 原始字符串(raw string),表示里面的 \
不会被转义。
例如:
path = "C:\newfolder\test" # 这个会报错,因为 \n 被当作换行了
path = r"C:\newfolder\test" # 正确,原样保留 \n
在正则中常出现 \d
、\w
这样的特殊字符,所以基本都会加上 r
,避免 \
被误解释。
✅ 总结:
现象 | 原因 |
---|---|
多个 r"..." 连续写 | Python 自动拼接多个字符串 |
为什么不用逗号 | 因为这不是多个值,是一个字符串在拼接 |
为什么加 r | 保证正则里的 \ 不会出错(原始字符串) |