Python中双引号与单引号问题:脚本运行时字符串引号显示异常求助
解答:Python格式化字符串中引号不一致的问题
Hey there! Let's break down why you're seeing mixed single and double quotes, and how to fix it.
问题原因
你代码里用的%r格式化符号,背后对应的是Python内置的repr()函数。这个函数的核心目的是生成可直接作为Python代码运行的字符串表示,所以它会智能选择引号类型来包裹字符串:
- 如果字符串本身包含单引号(比如你最后一行里的
"But it didn't sing."),repr()就会用双引号包裹它,这样就不用对字符串里的单引号做转义处理(比如写成didn\'t),让输出更整洁。 - 如果字符串里没有单引号,
repr()就默认用单引号包裹。
你看到的“每隔一个字符串显示为单引号”其实是巧合——刚好第三个字符串包含单引号,所以它用双引号,其他几个用单引号,看起来像是交替出现~
解决办法
如果你想让所有字符串的引号样式统一,可以根据需求选下面两种方式:
1. 改用%s格式符
%s对应str()函数,它会直接输出字符串的原始内容,不会额外添加引号(除非字符串本身自带):
formatter = "%s %s %s %s" print(formatter % (1, 2, 3, 4)) print(formatter % ("one", "two", "three", "four")) print(formatter % (True, False, False, True)) print(formatter % (formatter, formatter, formatter, formatter)) print(formatter % ( "I had this thing.", "That you could type up right.", "But it didn't sing.", "So I said goodnight." ))
2. 手动指定统一引号
如果还是希望每个字符串都被同一种引号包裹,可以在格式字符串里手动添加引号:
# 统一用单引号 formatter = "'%s' '%s' '%s' '%s'" print(formatter % (1, 2, 3, 4)) print(formatter % ("one", "two", "three", "four")) print(formatter % (True, False, False, True)) print(formatter % (formatter, formatter, formatter, formatter)) print(formatter % ( "I had this thing.", "That you could type up right.", "But it didn't sing.", "So I said goodnight." ))
换成双引号包裹也是一样的道理,只要调整格式字符串里的引号即可。
内容的提问来源于stack exchange,提问作者Yathartha
相关产品推荐
相关产品推荐

