简体   繁体   English

在python字符串中同时具有单引号和双引号

[英]Having both single and double quotation in a python string

Hi I'm trying to have a string that contains both single and double quotation in python -- ('"). The reason I need this expression is to use as an input to some external batch command. However, python always automatically corrects this to (\\' ").嗨,我正在尝试在 python 中有一个包含单引号和双引号的字符串 -- ('")。我需要这个表达式的原因是用作一些外部批处理命令的输入。但是,python 总是会自动更正这个到 (\\' ”)。 I wonder if there's a way to put a double quotation and a single quotation together as it is.我想知道是否有办法将双引号和单引号放在一起。 Thanks.谢谢。

Use triple quotes.使用三重引号。

"""Trip'le qu"oted"""

or要么

'''Ag'ain qu"oted'''

Keep in mind that just because Python repr sa string with backslashes, doesn't mean it's actually added any slashes to the string, it may just be showing special characters escaped.请记住,仅仅因为 Python repr sa 带有反斜杠的字符串,并不意味着它实际上在字符串中添加了任何斜杠,它可能只是显示转义的特殊字符。

Using an example from the Python tutorial:使用 Python 教程中的示例:

>>> len('"Isn\'t," she said.')
18
>>> len('''"Isn't," she said.''')
18

Even though the second string appears one character shorter because it doesn't have a backslash in it, it's actually the same length -- the backslash is just to escape the single quote in the single quoted string.尽管第二个字符串由于没有反斜杠而显得短了一个字符,但它实际上是相同的长度——反斜杠只是为了转义单引号字符串中的单引号。

Another example:另一个例子:

>>> for c in '''"Isn't," she said.''':
...     sys.stdout.write(c)
... 
"Isn't," she said.
>>> 

If you don't let Python format the string, you can see the string hasn't been changed, it was just Python trying to display it unambiguously.如果你不让 Python 格式化字符串,你可以看到字符串没有改变,只是 Python 试图明确地显示它。

See the tutorial section on strings .请参阅有关 strings教程部分

To add both the single and double quote on python use screened (escaped) quotes.要在 python 上添加单引号和双引号,请使用屏蔽(转义)引号。 Try this for example:试试这个,例如:

print(" just display ' and \" ")

The \\" tells python this is not the end of the quoted string. \\"告诉 python 这不是带引号的字符串的结尾。

Use triple-quoted strings:使用三引号字符串:

""" This 'string' contains "both" types of quote """
''' So ' does " this '''

The actual problem is , the print() statement doesn't print the \\ but when you refer to the value of the string in the interpreter, it displays a "\\" whenever an apostrophe is used .实际问题是,print() 语句不会打印\\,但是当您在解释器中引用字符串的值时,只要使用撇号,它就会显示“\\”。 For instance, refer the following code:例如,参考以下代码:

    >>> s = "She said, \"Give me Susan's hat\""
    >>> print(s)
    She said, "Give me Susan's hat"
    >>> s
    'She said, "Give me Susan\'s hat"'

This is irrespective of whether you use single, double or triple quotes to enclose the string.这与您使用单引号、双引号还是三引号将字符串括起来无关。

    >>> s = """She said, "Give me Susan's hat" """
    >>> s
    'She said, "Give me Susan\'s hat" '

Another way to include this :包括这个的另一种方法:

    >>> s = '''She said, "Give me Susan's hat" '''
    >>> s
    'She said, "Give me Susan\'s hat" '
    >>> s =  '''She said, "Give me Susan\'s hat" '''
    >>> s
    'She said, "Give me Susan\'s hat" '

So basically, python doesn't remove the \\ when you refer to the value of s but removes it when you try to print.所以基本上,当您引用 s 的值时,python 不会删除 \\,而是在您尝试打印时将其删除。 Despite this fact, when you refer to the length of s, it doesn't count the "\\".尽管如此,当你提到 s 的长度时,它不计算“\\”。 For eg.,例如,

    >>> s = '''"''"'''
    >>> s
    '"\'\'"'
    >>> print(s)
    "''"
    >>> len(s)
    4

This also confused me for more than a day, but I've digested it now.这也让我困惑了一天多,但我现在已经消化了。

First, let's understand that the string will output DOUBLE quotes if it passes DOUBLE the tests:首先,让我们了解如果字符串通过 DOUBLE 测试,它将输出双引号:

  1. Contains a single quote包含单引号
  2. Contains NO double quotes不包含双引号

That's the easiest manner to remember it.这是最容易记住的方式。

The literal "doesn't" passes the first test because of the apostrophe, which counts as a single quote.由于撇号,文字"doesn't"通过了第一个测试,这算作单引号。 Then, we re-examine it and find it does not contain any double quotes inside of the enclosure.然后,我们重新检查它,发现它的外壳内不包含任何双引号。 Therefore, the string literal outputs as a double quote:因此,字符串文字输出为双引号:

>>> "doesn't"
"doesn't"

There is no need to escape a single quote with a backslash in the output because the enclosure is composed of double quotes!没有必要在输出中用反斜杠转义单引号,因为外壳是由双引号组成的!

Now consider the literal '"Isn\\'t," they said.'现在考虑字面意思'"Isn\\'t," they said.' This literal passes the first test because it contains an apostrophe, even if it's escaped.这个文字通过了第一个测试,因为它包含一个撇号,即使它被转义了。 However, it also contains double quotes, so it fails the second test.但是,它也包含双引号,因此它无法通过第二个测试。 Therefore, it outputs as a single quote:因此,它输出为单引号:

>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

And because the enclosure is composed of single quotes, the escape is needed in the output.并且由于外壳由单引号组成,因此输出中需要转义符。

If it weren't for the backslash in the output, the EOL (end of line) would have been reached while scanning the literal.如果不是输出中的反斜杠,扫描文字时就会到达 EOL(行尾)。

Finally, consider "\\"Isn't,\\" they said."最后,考虑"\\"Isn't,\\" they said."

There is a single quote inside of the literal, so it does pass the first test...but fails the second.文字中有一个单引号,所以它确实通过了第一个测试……但第二个测试失败了。 The output should enclose the string literal in single quotes:输出应将字符串文字括在单引号中:

>>> "\"Isn't,\" they said."
'"Isn\'t," they said.'

Therefore, the escape is needed to prevent a premature EOL.因此,需要逃逸以防止过早的 EOL。

Although its more verbose, an alternative way would be to do the following:虽然它更冗长,但另一种方法是执行以下操作:

str1 = 'the part that has double "s" in it'

str1 = str1 + " the part that has single 's' in it"

You can either (1) enclose the string in double quotes and escape the double quotes with a \\ or (2) enclose the string in single quotes and escape the single quotes with a \\ .您可以 (1) 将字符串括在双引号中并用\\转义双引号或 (2) 将字符串括在单引号中并用\\转义单引号。 For example:例如:

>>> print('She is 5\' 6" tall.')
She is 5' 6" tall.
>>> print("He is 5' 11\" tall.")
He is 5' 11" tall.

In f-string, I can't use back slash.在 f-string 中,我不能使用反斜杠。 At that time, Using chr() may be solution!那时,使用 chr() 可能是解决方案!

print(f"- tokenizer: {' '.join(str(type(tokenizer)).split(chr(39))[1:-1])}")

Unicode HOWTO Unicode HOWTO

In certain cases, using triple quotes seems to not work for me.在某些情况下,使用三重引号似乎对我不起作用。

For instance, I once confronted with the problem to manipulate this script to be more dynamic.例如,我曾经遇到过将这个脚本操作得更加动态的问题。

listed = drive.ListFile({'q': "title contains '.mat' and '1GN8xQDTW4wC-dDrXRG00w7CymjI' in parents"}).GetList()

In the part after 'q': , there is a string with double and single quotes.'q':之后的部分,有一个带有双引号和单引号的字符串。 So, I intend to independently change the file type ('.mat) and the folder ID ('1GN...').因此,我打算独立更改文件类型 ('.mat) 和文件夹 ID ('1GN...')。

Dealing with the issue, I use .format to manipulate the script above and turn it into this one处理这个问题,我使用.format来操作上面的脚本并将其变成这个

listed = drive.ListFile({'q': "title contains '{}' and '{}' in parents".format(file_type, folder_id)}).GetList()

May it helps to give certain clue if using triple quotes is not possible for you.如果您无法使用三重引号,可能有助于提供某些线索。

cheers!干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python 中的正则表达式:允许双引号和单引号 - Regex in Python: Allow double and single quotation marks 在 python 字符串变量中包括单引号和双引号 - Include both single quote and double quote in python string variable 如何在python中存储包含单引号(')和双引号(“)的字符串 - How to store a string containing both single quote( ' ) and double quote( " ) in python 如何格式化带有双引号和单引号的python字符串 - How to format python string with both double and single quotes 如何在python字符串中同时使用单引号和双引号 - How do I use both single and double quotes in a python string 简单的字符串问题 - 字符串中的单引号和双引号只是将字符串分成几个部分 - simple string question - the Single quotation marks and Double quotation marks inside the string just make the string into several parts 用单引号将Python字符串分割 - Split Python String by single quotation marks python 正则表达式:提取单引号或双引号之间的文本 - python regex: extracting texts between single or double quotation marks 在Python未编码的字符串中查找和替换两种引号样式 - Find and replace both quotation styles in Python unicoded string 如何在python列表中的字符串周围替换双引号? - How to replace the double quotation marks around a string in python list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM