473,545 Members | 2,788 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to strip of mulitiple white spaces.

8 New Member
Hi all,

Suppose I am having a string like this.

mystr = " I have five spaces after this and 3 spaces after this and 10 spaces after this. How to remove this muliple whitespaces "

I just want to remove this multiple whitespaces and need the output like this

I have five spaces after this and 3 spaces after this and 10 spaces after this. How to remove this muliple whitespaces

Can anyone help me out please?
Jan 19 '07 #1
5 51360
shajias
8 New Member
Since I couldnt retain the format which I wanted in the mail, I am rewording my question.

Hi all,

I am having adjacent multiple white spaces(both leading, trailing and in the middle) in a string. I want to strip off all the multiple white spaces and need to substitute multiple whitespaces by one white space there. Is there any way for that.?

I know that leading and trailing whitespaces can be stripped by rstrip and lstrip. But I couldnt do anythign with multiple whitespaces in the middle of a string

Can anybody help me out please?

~Sas
Jan 19 '07 #2
dshimer
136 Recognized Expert New Member
I'm not sure this is particularly elegant, but it was my first thought.
Expand|Select|Wrap|Line Numbers
  1. origstrg='there   are some  places   with many      spaces'
  2. newstrg=''
  3. for word in origstrg.split():
  4.     newstrg=newstrg+' '+word
  5. print newstrg
  6.  
which should come up as...
there are some places with many spaces
Jan 19 '07 #3
ghostdog74
511 Recognized Expert Contributor
Since I couldnt retain the format which I wanted in the mail, I am rewording my question.

Hi all,

I am having adjacent multiple white spaces(both leading, trailing and in the middle) in a string. I want to strip off all the multiple white spaces and need to substitute multiple whitespaces by one white space there. Is there any way for that.?

I know that leading and trailing whitespaces can be stripped by rstrip and lstrip. But I couldnt do anythign with multiple whitespaces in the middle of a string

Can anybody help me out please?

~Sas


1) you can strip off trailing and leading whitespaces using strip(). So there's no need for lstrip,rstrip
eg
Expand|Select|Wrap|Line Numbers
  1. >>> s = "    a string with leading and trailing spaces    "
  2. >>> s.strip()
  3. 'a string with leading and trailing spaces'
  4.  
2) if you know the number of multiple white spaces in the middle, eg 2 white spaces, you can use replace() , eg for 2 white spaces
Expand|Select|Wrap|Line Numbers
  1. >>> s = "a string  with multiple  white spaces"
  2. >>> s.replace("  "," ")
  3. 'a string with multiple white spaces'
  4. >>> 
  5.  
3) if you don't know the number of white spaces in the middle, you can use split(), which i think is most straight forward :)
Expand|Select|Wrap|Line Numbers
  1. >>> s = "a string  with multiple    white          spaces"
  2. >>> s.split()
  3. ['a', 'string', 'with', 'multiple', 'white', 'spaces']
  4. >>> ' '.join(s.split())
  5. 'a string with multiple white spaces'
  6.  
4) you can also use regular expression module eg
Expand|Select|Wrap|Line Numbers
  1. >>> import re
  2. >>> s = "a string  with multiple    white          spaces"
  3. >>> re.sub("\s+" , " ", s)
  4. 'a string with multiple white spaces'
  5.  
Jan 19 '07 #4
bvdet
2,851 Recognized Expert Moderator Specialist
ghostdog,

Your option #3 also eliminates the leading and trailing spaces, therefore may be the best solution.
Expand|Select|Wrap|Line Numbers
  1. >>> s = "      a string  with multiple    white          spaces    "
  2. >>> " ".join(s.split())
  3. 'a string with multiple white spaces'
The string method join is very efficient.
Jan 19 '07 #5
bartonc
6,596 Recognized Expert Expert
ghostdog,

Your option #3 also eliminates the leading and trailing spaces, therefore may be the best solution.
Expand|Select|Wrap|Line Numbers
  1. >>> s = "      a string  with multiple    white          spaces    "
  2. >>> " ".join(s.split())
  3. 'a string with multiple white spaces'
The string method join is very efficient.
That's exactly how I'd do it.
Jan 19 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

5
3295
by: qwweeeit | last post by:
Hi all, I need to limit as much as possible the lenght of a source line, stripping white spaces (except indentation). For example: .. . max_move and AC_RowStack.acceptsCards ( self, from_stack, cards ) must be reduced to: .. . max_move and AC_RowStack.acceptsCards(self,from_stack,cards) My solution has been (wrogly):...
2
2232
by: Malcolm Dew-Jones | last post by:
I am looking at xslt 1.0 and trying to understand if empty text nodes are supposed to be stripped or not as the default behaviour. 3.4 starts by listing rules for when white space is not stripped and then says "Otherwise the text node is stripped". which appears to contradict a later paragraph that discusses the details of the selection...
17
9103
by: Stanimir Stamenkov | last post by:
Is it possible to make two inline elements to appear adjacent stripping any white space appearing in between in the source? Example: <span class="adj">1</span> <span class="adj">2</span> <span class="adj">3</span> --
11
14981
by: gopal srinivasan | last post by:
Hi, I have a text like this - "This is a message containing tabs and white spaces" Now this text contains tabs and white spaces. I want remove the tabs and white spaces(if it more than once between two words). Is there any function we have in C which will find out the tabs and white spaces and returns the...
3
3355
by: Prince | last post by:
I have some <RequiredFieldValidator> on my page and everything works fine except that there are lots of white spaces between the web server controls that are being validated. I've set the Display properties for all the controls to "Dynamic" and still I can't get rid of the white spaces between controls. It's as if there are bunch of <br>...
4
3571
by: Andreas Prilop | last post by:
How many spaces should be displayed in A <span style="display:none">x</span> B between "A" and "B"? I notice that Mozilla displays one space and Internet Explorer (5 & 6) displays two spaces. See http://www.unics.uni-hannover.de/nhtcapri/temp/white-space.html for a cumulative effect. Why is this important? Instead of "span", think of...
4
1496
by: Nathan Sokalski | last post by:
I have two asp:ImageMaps in a table cell as follows: <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="center"> <asp:ImageMap ID="mapBanner" runat="server" BorderWidth="0px" Height="82px" ImageUrl="../images/top_banner.jpg" Width="1000px" style="margin:0px;padding:0px;"> <asp:RectangleHotSpot...
12
7199
by: JA | last post by:
Is there a way to remove all the white space in the fields? I have been using Find-and-replace - looking for 2 or 3 or 4 or 10 spaces and replacing them with none. I don't want to replace single spaces, those are the spaces between the words. But most of what is in the fields has been cut-n-pasted from online forms, and the results can be...
3
1906
by: ayan4u | last post by:
well i need to deal with white spaces in charecter arrays... with static arrays its fine.. char ss; cin.getline(ss, sizeof ss); .... //deals with white spaces
0
7499
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7689
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7456
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6022
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5359
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3490
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1919
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
743
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.