标签归档:string-literals

python:SyntaxError:扫描字符串文字时停产

问题:python:SyntaxError:扫描字符串文字时停产

我有上述错误 s1="some very long string............"

有人知道我在做什么错吗?

I have the above-mentioned error in s1="some very long string............"

Does anyone know what I am doing wrong?


回答 0

您没有"在行尾放置a 。

"""如果要执行此操作,请使用:

""" a very long string ...... 
....that can span multiple lines
"""

You are not putting a " before the end of the line.

Use """ if you want to do this:

""" a very long string ...... 
....that can span multiple lines
"""

回答 1

我遇到了这个问题-我最终弄清楚了原因是我\在字符串中包含了字符。如果您有任何一个,请与他们“转义” \\,它应该可以正常工作。

I had this problem – I eventually worked out that the reason was that I’d included \ characters in the string. If you have any of these, “escape” them with \\ and it should work fine.


回答 2

(假设您的字符串中没有/想要换行…)

这串真的多久了?

我怀疑从文件或从命令行读取的行的长度是有限制的,并且由于行的结尾被解析器截断,因此会看到类似s1="some very long string..........(不带结尾")的内容,从而引发解析错误?

您可以通过在源代码中转义换行符,将长行分成多行:

s1="some very long string.....\
...\
...."

(Assuming you don’t have/want line breaks in your string…)

How long is this string really?

I suspect there is a limit to how long a line read from a file or from the commandline can be, and because the end of the line gets choped off the parser sees something like s1="some very long string.......... (without an ending ") and thus throws a parsing error?

You can split long lines up in multiple lines by escaping linebreaks in your source like this:

s1="some very long string.....\
...\
...."

回答 3

在我的情况下,我\r\n在单引号中包含字典字符串。我取代的所有实例\r\\r\n\\n它固定我的问题,正确地返回在eval’ed字典逃脱换行符。

ast.literal_eval(my_str.replace('\r','\\r').replace('\n','\\n'))
  .....

In my situation, I had \r\n in my single-quoted dictionary strings. I replaced all instances of \r with \\r and \n with \\n and it fixed my issue, properly returning escaped line breaks in the eval’ed dict.

ast.literal_eval(my_str.replace('\r','\\r').replace('\n','\\n'))
  .....

回答 4

我遇到了类似的问题。我有一个包含Windows中文件夹路径的字符串,例如C:\Users\,问题是\转义字符,因此要在字符串中使用它,您需要再添加一个\

不正确: C:\Users\

正确: C:\\\Users\\\

I faced a similar problem. I had a string which contained path to a folder in Windows e.g. C:\Users\ The problem is that \ is an escape character and so in order to use it in strings you need to add one more \.

Incorrect: C:\Users\

Correct: C:\\\Users\\\


回答 5

我也有这个问题,尽管这里有答案,但我想在/不应该有空白的地方对此做一个重要 说明。

I too had this problem, though there were answers here I want to an important point to this after / there should not be empty spaces.Be Aware of it


回答 6

我也有此确切的错误消息,对我来说,此问题已通过添加“ \”来解决

事实证明,我的长字符串在结尾处被分解成大约八行,并带有“ \”,但在一行上缺少“ \”。

Python IDLE没有指定此错误所在的行号,但是它以红色突出显示了完全正确的变量赋值语句,这使我不满意。实际变形的字符串语句(多行长为“ \”)与突出显示的语句相邻。也许这会帮助别人。

I also had this exact error message, for me the problem was fixed by adding an ” \”

It turns out that my long string, broken into about eight lines with ” \” at the very end, was missing a ” \” on one line.

Python IDLE didn’t specify a line number that this error was on, but it red-highlighted a totally correct variable assignment statement, throwing me off. The actual misshapen string statement (multiple lines long with ” \”) was adjacent to the statement being highlighted. Maybe this will help someone else.


回答 7

就我而言,我使用Windows,因此必须使用双引号而不是单引号。

C:\Users\Dr. Printer>python -mtimeit -s"a = 0"
100000000 loops, best of 3: 0.011 usec per loop

In my case, I use Windows so I have to use double quotes instead of single.

C:\Users\Dr. Printer>python -mtimeit -s"a = 0"
100000000 loops, best of 3: 0.011 usec per loop

回答 8

我在postgresql函数中遇到此错误。我有一个较长的SQL,使用\分成多行,以提高可读性。但是,这就是问题所在。我删除了所有内容,并将它们放在一行中以解决此问题。我正在使用pgadmin III。

I was getting this error in postgresql function. I had a long SQL which I broke into multiple lines with \ for better readability. However, that was the problem. I removed all and made them in one line to fix the issue. I was using pgadmin III.


回答 9

就Mac OS X而言,我有以下陈述:

model.export_srcpkg(platform, toolchain, 'mymodel_pkg.zip', 'mymodel.dylib’)

我收到错误:

  File "<stdin>", line 1
model.export_srcpkg(platform, toolchain, 'mymodel_pkg.zip', 'mymodel.dylib’)
                                                                             ^
SyntaxError: EOL while scanning string literal

在我更改为:

model.export_srcpkg(platform, toolchain, "mymodel_pkg.zip", "mymodel.dylib")

有效…

大卫

In my case with Mac OS X, I had the following statement:

model.export_srcpkg(platform, toolchain, 'mymodel_pkg.zip', 'mymodel.dylib’)

I was getting the error:

  File "<stdin>", line 1
model.export_srcpkg(platform, toolchain, 'mymodel_pkg.zip', 'mymodel.dylib’)
                                                                             ^
SyntaxError: EOL while scanning string literal

After I change to:

model.export_srcpkg(platform, toolchain, "mymodel_pkg.zip", "mymodel.dylib")

It worked…

David


回答 10

您可以尝试以下方法:

s = r'long\annoying\path'

You can try this:

s = r'long\annoying\path'

回答 11

variable(s1)跨多行。为了做到这一点(即您希望您的字符串跨越多行),必须使用三引号(“”“)。

s1="""some very long 
string............"""

Your variable(s1) spans multiple lines. In order to do this (i.e you want your string to span multiple lines), you have to use triple quotes(“””).

s1="""some very long 
string............"""

回答 12

在这种情况下,三个单引号或三个双引号都可以使用!例如:

    """Parameters:
    ...Type something.....
    .....finishing statement"""

要么

    '''Parameters:
    ...Type something.....
    .....finishing statement'''

In this case, three single quotations or three double quotations both will work! For example:

    """Parameters:
    ...Type something.....
    .....finishing statement"""

OR

    '''Parameters:
    ...Type something.....
    .....finishing statement'''

回答 13

以前的大多数答案都是正确的,我的答案与aaronasterling非常相似,您也可以用3个单引号s1 =”’一些很长的字符串………”’

Most previous answers are correct and my answer is very similar to aaronasterling, you could also do 3 single quotations s1=”’some very long string…………”’


回答 14

访问任何硬盘目录时,我都遇到了同样的问题。然后我以这种方式解决了。

 import os
 os.startfile("D:\folder_name\file_name") #running shortcut
 os.startfile("F:") #accessing directory

上图显示了错误和已解决的输出。

I had faced the same problem while accessing any hard drive directory. Then I solved it in this way.

 import os
 os.startfile("D:\folder_name\file_name") #running shortcut
 os.startfile("F:") #accessing directory

The picture above shows an error and resolved output.


Python中的Windows路径

问题:Python中的Windows路径

例如,代表Windows目录的最佳方法是什么"C:\meshes\as"?我一直在尝试修改脚本,但是它永远无法正常工作,因为我似乎无法正确获得目录,我想是因为它'\'充当转义符?

What is the best way to represent a Windows directory, for example "C:\meshes\as"? I have been trying to modify a script but it never works because I can’t seem to get the directory right, I assume because of the '\' acting as escape character?


回答 0

您可以始终使用:

'C:/mydir'

这适用于linux和Windows。其他可能性是

'C:\\mydir'

如果您对某些名称有疑问,也可以尝试使用原始字符串文字:

r'C:\mydir'

但是,最佳实践是使用os.path始终为您的操作系统选择正确配置的模块功能:

os.path.join(mydir, myfile)

从python 3.4开始,您还可以使用pathlib模块。这等同于以上内容:

pathlib.Path(mydir, myfile)

要么

pathlib.Path(mydir) / myfile

you can use always:

'C:/mydir'

this works both in linux and windows. Other posibility is

'C:\\mydir'

if you have problems with some names you can also try raw string literals:

r'C:\mydir'

however best practice is to use the os.path module functions that always select the correct configuration for your OS:

os.path.join(mydir, myfile)

From python 3.4 you can also use the pathlib module. This is equivelent to the above:

pathlib.Path(mydir, myfile)

or

pathlib.Path(mydir) / myfile

回答 1

使用os.path模块。

os.path.join( "C:", "meshes", "as" )

或使用原始字符串

r"C:\meshes\as"

我也建议不要在路径或文件名中使用空格。您可以在字符串中使用双反斜杠。

"C:\\meshes\\as.jpg"

Use the os.path module.

os.path.join( "C:", "meshes", "as" )

Or use raw strings

r"C:\meshes\as"

I would also recommend no spaces in the path or file names. And you could use double backslashes in your strings.

"C:\\meshes\\as.jpg"

回答 2

是的,\在Python中,字符串文字表示转义序列的开始。在您的路径中,您有一个有效的两个字符的转义序列\a,该序列被折叠成一个字符,即ASCII Bell

>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess

其他常见的转义序列包括\t(制表符),\n(换行),\r(回车):

>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']

如您所见,在所有这些示例中,反斜杠和文字中的下一个字符被组合在一起以在最终字符串中形成单个字符。Python的转义序列的完整列表在这里

有多种解决方法:

  1. Python将不会处理与前缀字符串文字的转义序列rR

    >>> r'C:\meshes\as'
    'C:\\meshes\\as'
    >>> print(r'C:\meshes\as')
    C:\meshes\as
    
  2. Windows上的Python也应处理正斜杠。

  3. 您可以使用os.path.join

    >>> import os
    >>> os.path.join('C:', os.sep, 'meshes', 'as')
    'C:\\meshes\\as'
    
  4. …或较新的pathlib模块

    >>> from pathlib import Path
    >>> Path('C:', '/', 'meshes', 'as')
    WindowsPath('C:/meshes/as')
    

Yes, \ in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence \a, which is collapsed into one character that is ASCII Bell:

>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess

Other common escape sequences include \t (tab), \n (line feed), \r (carriage return):

>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']

As you can see, in all these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Python’s escape sequences is here.

There are a variety of ways to deal with that:

  1. Python will not process escape sequences in string literals prefixed with r or R:

    >>> r'C:\meshes\as'
    'C:\\meshes\\as'
    >>> print(r'C:\meshes\as')
    C:\meshes\as
    
  2. Python on Windows should handle forward slashes, too.

  3. You could use os.path.join

    >>> import os
    >>> os.path.join('C:', os.sep, 'meshes', 'as')
    'C:\\meshes\\as'
    
  4. … or the newer pathlib module

    >>> from pathlib import Path
    >>> Path('C:', '/', 'meshes', 'as')
    WindowsPath('C:/meshes/as')
    

回答 3

使用PowerShell

在Windows中,只要将PowerShell用作命令行界面,就可以/在所有地方像Linux或macOS一样在路径中使用。它预装在Windows上,并且支持许多Linux命令,例如lscommand。

如果使用Windows命令提示符(cmd在Windows“开始”菜单中键入时显示的命令提示符),则需要在其中指定路径\。您可以/在所有其他地方使用路径(代码编辑器,Python交互模式等)。

Use PowerShell

In Windows, you can use / in your path just like Linux or macOS in all places as long as you use PowerShell as your command-line interface. It comes pre-installed on Windows and it supports many Linux commands like ls command.

If you use Windows Command Prompt (the one that appears when you type cmd in Windows Start Menu), you need to specify paths with \ just inside it. You can use / paths in all other places (code editor, Python interactive mode, etc.).


回答 4

如果您想粘贴其他来源的Windows路径(例如,文件资源管理器),则可以通过input()python控制台中的调用来粘贴:

>>> input()
D:\EP\stuff\1111\this_is_a_long_path\you_dont_want\to_type\or_edit_by_hand
'D:\\EP\\stuff\\1111\\this_is_a_long_path\\you_dont_want\\to_type\\or_edit_by_hand'

然后复制结果

In case you’d like to paste windows path from other source (say, File Explorer) – you can do so via input() call in python console:

>>> input()
D:\EP\stuff\1111\this_is_a_long_path\you_dont_want\to_type\or_edit_by_hand
'D:\\EP\\stuff\\1111\\this_is_a_long_path\\you_dont_want\\to_type\\or_edit_by_hand'

Then just copy the result