0

\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))

与える

\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'
4

1 に答える 1

8

リテラルの後にリテラルが続く\nのではなく、改行でよろしいですか?その場合は、次のようにします。\n

s = r'\nthis is a string'
s = s.strip()
print s
s = s.strip(r'\n')
print s

おそらくより良い方法は、\nストリッピングの前に開始するかどうかを確認してから、スライスを使用することです。

if s.startswith(r'\n'): s = s[2:]

またはさらに堅牢に、re.sub

re.sub(r'^(?:\\n)+','',r'\n\nfoobar')

あなたが上で説明した症状に基づいて、私はこれが事実であるとほぼ確信しています。

于 2012-11-05T22:12:31.893 に答える