我想\n
从头开始删除这样的行\n id int(10) NOT NULL
.我试过strip()
,rstrip()
,lstrip()
replace('\n', '')
.我不明白.我究竟做错了什么?
print(column)
print(column.__class__)
x = column.rstrip('\n')
print(x)
x = column.lstrip('\n')
print(x)
x = column.strip('\n')
print(x)
print(repr(column))
Run Code Online (Sandbox Code Playgroud)
给
\n id int(10) NOT NULL
<type 'str'>
\n id int(10) NOT NULL
\n id int(10) NOT NULL
\n id int(10) NOT NULL
\n id int(10) NOT NULL
'\\n `id` int(10) NOT NULL'
Run Code Online (Sandbox Code Playgroud)
你确定这\n
是一个换行符而不是文字\
后跟文字n
吗?在这种情况下,你想要:
s = r'\nthis is a string'
s = s.strip()
print s
s = s.strip(r'\n')
print s
Run Code Online (Sandbox Code Playgroud)
可能更好的方法是检查它是否\n
在剥离之前开始,然后使用切片:
if s.startswith(r'\n'): s = s[2:]
Run Code Online (Sandbox Code Playgroud)
甚至更强大,re.sub
:
re.sub(r'^(?:\\n)+','',r'\n\nfoobar')
Run Code Online (Sandbox Code Playgroud)
根据你上面描述的症状,我几乎是肯定的.