【问题标题】:Replacing backward slash in python / pandas在 python / pandas 中替换反斜杠
【发布时间】:2018-11-27 00:07:05
【问题描述】:

我正在尝试在一些csv 文件中用/ 替换一些\ 字符(因为我正在从Windows 迁移到Linux,并且需要修改.csv 文件中列出的路径名。)。

我有这个:

 import pandas as pd
 file = 'my_file.csv'
 df = pd.read_csv(file)
 df = df.replace('\','/')
 df.to_csv(file)

但我收到此错误:

file "<ipython-input-29-9556415d69a6>", line 5
    df = df.replace('\','/')
                            ^
SyntaxError: EOL while scanning string literal

我可以替换任何其他字符,但 \ 会导致问题,大概是因为它试图将字符串解释为路径?

我做错了什么??

【问题讨论】:

  • df.replace('\\','/') 在您不想使用时转义反斜杠

标签: python string pandas path


【解决方案1】:

在字符串 (\) 中使用或引用反斜杠时,必须用另一个反斜杠对其进行转义:

>>> s = '\just some test\'
SyntaxError: EOL while scanning string literal
>>> s = '\\just some test\\'
>>> s.replace('\\', '/')
'/just some test/'

Python lexical analysis - 字符串字面量

反斜杠 (\) 字符用于转义具有特殊含义的字符,例如换行符、反斜杠本身或引号字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 2020-08-24
    • 1970-01-01
    • 2012-04-14
    相关资源
    最近更新 更多