[英]Understanding string generation of double vs single quotes
I'm trying to understand why sometimes double quotes are being generated vs single quotes for my list creation function.我试图理解为什么有时会为我的列表创建 function 生成双引号而不是单引号。 I have a function that I've used on multiple text files and normally the output is a list with single quotes, but now double quotes are generated (when I need single).我有一个 function 我在多个文本文件中使用过,通常 output 是一个带有单引号的列表,但现在生成了双引号(当我需要单引号时)。
Would someone be able to help me understand why double quotes might be generated here and/or a way to just force the single quotes?有人可以帮助我理解为什么这里可能会生成双引号和/或强制使用单引号的方法吗?
for below structure is :
string_text is str
text_list is list
list_text is list
def view(string_text):
text_list = []
for t in list_text:
text_list.append(string_text + """ more text """ + t +
""" more text """)
return text_list
text_list = view(string_text)
The append is specific to my use case, but you get the idea. append 特定于我的用例,但你明白了。 Double quotes are generated for text_list.为 text_list 生成双引号。
list_text sample = ['a','b','c']
It is not an explanation of why this occurs, but maybe a solution: If you wrap another str()
around your string (double or single quoted), the result should always be single quoted, at least when I tried it.这不是为什么会发生这种情况的解释,但可能是一个解决方案:如果您将另一个str()
包裹在您的字符串周围(双引号或单引号),则结果应该始终是单引号,至少在我尝试时是这样。
So let's turn your code into something which can directly be pasted into a python console window:因此,让我们将您的代码转换为可以直接粘贴到 python 控制台 window 的内容:
def view(string_text):
text_list = []
for t in list_text:
text_list.append(string_text + """ more text """ + t +
""" more text """)
return text_list
list_text = ['a', 'b', 'c']
text_list = view('123')
text_list
shows节目
['123 more text a more text ', '123 more text b more text ', '123 more text c more text ']
Why?为什么? Because the string representation of a string uses '
until there is a '
contained in the string.因为字符串的字符串表示使用'
直到字符串中包含'
。 Then it uses "
for delimiting the string.然后它使用"
来分隔字符串。
Simpler examples are更简单的例子是
>>> "'"
"'"
>>> '"'
'"'
>>> "'\""
'\'"'
But it shouldn't make a difference.但这不应该有所作为。 As said, this is just the string representation of a string which exists in your program.如前所述,这只是您程序中存在的字符串的字符串表示形式。 These delimiters aren't really in the string itself.这些定界符实际上并不在字符串本身中。 See the difference between what str()
and repr()
do, respectively.分别查看str()
和repr()
的区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.