Remove Multiple Whitespace in Python

Jika ingin melakukan penghapusan multiple whitespace, dapat dilakukan dengan cara ini ..

origstrg='there   are some  places   with many      spaces'
newstrg=''
for word in origstrg.split():
     newstrg=newstrg+' '+word
print newstrg

simple tho..๐Ÿ™‚
nah, cara kerja fungsi split itu adalah merecognize setiap string menjadi token2..disimpan dalam bentuk array, lalu ditulis kembali.. lebih konkretnya, lihat ini..

# >>> s = "a string  with multiple    white          spaces"
# >>> s.split()
# ['a', 'string', 'with', 'multiple', 'white', 'spaces']
# >>> ' '.join(s.split())
# 'a string with multiple white spaces'

Cara lain untuk remove whitespace, kamu juga bisa pakai ini

' '.join("Please \n don't \t hurt \x0b me.".split())
"Please don't hurt me."

dan juga bisa pake regular ekspression

#>>> import re
# >>> s = "a string  with multiple    white          spaces"
# >>> re.sub("\s+" , " ", s)
# 'a string with multiple white spaces'

One thought on “Remove Multiple Whitespace in Python”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s