|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
snow-white spaces!
Hi,
Suppose I've a large text file and I want to wipe out all the whitespaces present in it....this cld be done using replace but then it wld be a daunting task to remove all the whitespaces if I sit to write separate replaces for \t,\n,spaces,etc..... Is there any way by which I can achieve it at one go??? Thanks & Rgds, Subha ![]() |
|
#2
|
||||
|
||||
|
Use a regular expression perhaps?
Code:
#!/usr/bin/env python
import re
reg = re.compile('\s+')
line = """ This is a line with
lots of spaces and tabs and
new lines """
print "BEFORE REPLACEMENT"
print line
print "\nAFTER REPLACEMENT"
line2 = reg.sub("", line)
print line2
__________________
Up the Irons What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home. "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest Down with Sharon Osbourne Puzzle of the Month solved by Keath and KevinADC, superior perl programmers of the month |
|
#3
|
||||
|
||||
|
Just to give you the option, here are a few other ways. It's not as bad as you might have thought
.Code:
>>> from string import whitespace as whitespaces >>> >>> sample = 'Hello World!' >>> >>> for character in whitespaces: ... sample = sample.replace(character, '') ... >>> sample 'HelloWorld!' >>> >>> sample = 'Hello World!' >>> >>> results = [] >>> >>> for letter in sample: ... if letter not in whitespaces: results.append(letter) ... >>> results ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd', '!'] >>> >>> ''.join(results) 'HelloWorld!' >>> >>> [letter for letter in sample if letter not in whitespaces] ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd', '!'] >>> Particularly fond of the last one, it just reads so nicely . Enjoy!Mark. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > snow-white spaces! |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|