Boşlukları nasıl kırpabilirim?

Bir dizeden beyaz boşlukları (boşluklar ve sekmeler) kırpacak bir Python işlevi var mı?

Örnek: \t örnek dize\törnek dize

Çözüm

Her iki tarafta da beyaz boşluk:

s = "  \t a string example\t  "
s = s.strip()

Sağ tarafta beyaz boşluk:

s = s.rstrip()

Sol tarafta beyaz boşluk:

s = s.lstrip()

thedz]1'in belirttiği gibi, bu işlevlerden herhangi birine rastgele karakterleri ayıklamak için aşağıdaki gibi bir argüman sağlayabilirsiniz:

s = s.strip(' \t\n\r')

Bu, boşluk, \t, \n veya \r karakterlerini dizenin sol tarafından, sağ tarafından veya her iki tarafından çıkarır.

Yukarıdaki örnekler dizelerin yalnızca sol ve sağ taraflarından dizeleri kaldırır. Bir dizginin ortasındaki karakterleri de kaldırmak istiyorsanız, re.subu deneyin:

import re
print re.sub('[\s+]', '', s)

Bunun çıktısı alınmalı:

astringexample
Yorumlar (11)

Baştaki ve sondaki boşluklar için:

s = '   foo    \t   '
print s.strip() # prints "foo"

Aksi takdirde, düzenli bir ifade çalışır:

import re
pat = re.compile(r'\s+')
s = '  \t  foo   \t   bar \t  '
print pat.sub('', s) # prints "foobar"
Yorumlar (3)
#how to trim a multi line string or a file

s=""" line one
\tline two\t
line three """

#line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space.

s1=s.splitlines()
print s1
[' line one', '\tline two\t', 'line three ']

print [i.strip() for i in s1]
['line one', 'line two', 'line three']

#more details:

#we could also have used a forloop from the begining:
for line in s.splitlines():
    line=line.strip()
    process(line)

#we could also be reading a file line by line.. e.g. my_file=open(filename), or with open(filename) as myfile:
for line in my_file:
    line=line.strip()
    process(line)

#moot point: note splitlines() removed the newline characters, we can keep them by passing True:
#although split() will then remove them anyway..
s2=s.splitlines(True)
print s2
[' line one\n', '\tline two\t\n', 'line three ']
Yorumlar (0)