简体   繁体   English

替换python / pandas中的反斜杠

[英]Replacing backward slash in python / pandas

I am trying to replace some \\ characters with / in some csv files (because I'm moving from windows to linux and need to modify pathnames that are listed in the .csv files.). 我试图在某些csv文件中用/替换一些\\字符(因为我正从Windows迁移到linux,并且需要修改.csv文件中列出的路径名。)。

I have this: 我有这个:

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

but I get this error: 但是我得到这个错误:

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

I can replace any other character but teh \\ causes problems, presumably because it is trying to interpret the string as a path? 我可以替换任何其他字符,但teh \\会引起问题,大概是因为它试图将字符串解释为路径?

What am I doing wrong?? 我究竟做错了什么??

When using or referring a backslash in a string ( \\ ), it has to be escaped by another backslash: 在字符串( \\ )中使用或引用反斜杠时,必须使用另一个反斜杠对其进行转义:

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

Python lexical analysis - String literals Python词汇分析 -字符串文字

The backslash (\\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. 反斜杠(\\)字符用于转义具有特殊含义的字符,例如换行符,反斜杠本身或引号字符。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM