Skip to main content
 首页 » 编程设计

python之我想删除以下字符串 "Production and nonsupervisory employees\r\n\n\n"之后的所有内容

2025年05月04日29落叶无声

我想去掉 python 中\之后的字符串中的字符

df5['Abbreviation'] = df5['Abbreviation'].str.strip('\') 
df5['Data Type'] = df5['Data Type'].str.strip('\') 

错误信息:

File "<ipython-input-150-c7763a76caaf>", line 1 
 
    df5['Abbreviation'] = df5['Abbreviation'].str.strip('\') 
                                                            ^ 
SyntaxError: EOL while scanning string literal 

请您参考如下方法:

你不能在不转义的情况下在字符串文字中只有一个 \ (或在末尾,或只有奇数个的字符串)(因为它会转义右引号), 所以你必须转义它:

...str.strip('\\') 

要删除反斜杠后的所有内容,您可以使用apply 和split:

rem = lambda s : s.split('\\')[0] + '\\' 
 
df5['Abbreviation'] = df5['Abbreviation'].apply(rem) 
df5['Data Type'] = df5['Data Type'].apply(rem) 

此外,正如@G.Anderson 指出的那样,如果您的字符串与标题中的字符串相似,您可以只使用 ...str.strip(),在这种情况下,您的代码可能是:

df5['Abbreviation'] = df5['Abbreviation'].apply(str.strip) 
df5['Data Type'] = df5['Data Type'].apply(str.strip)