2

I am using this code to separate words into a list. The while loop is used to remove any blank spaces that come up, they will be elements with just a ''. The problem is even after I run the while loop there are still elements with just ''. I believe they are due to whitespaces and indentations. The while loop does get rid of about 2/3 of these spaces. Is there a way just to get the words separated? I don't want any blank elements because when I run a loop on them later I get a string index out of range when I reference mylist[i][0].

str = fpin.read()
mylist = re.split('[ \n]', str)
i = 0
while(i < len(mylist)):
if mylist[i] == '':
 del mylist[i]
i = i + 1
BenMorel
36.9k52 gold badges208 silver badges339 bronze badges
asked Jun 26, 2014 at 5:29
2
  • 1
    Since no one mentioned it directly yet: The empty strings are from when two spaces are next to each other, and there's nothing in between. The answers below will tell you how to deal with that. Commented Jun 26, 2014 at 5:37
  • In general, in Python, it is usually recommended to make a copy of a list that has just what you want in it, rather than to loop over an existing list and delete things from it. Simply using the .split() will eat up multiple whitespace characters, so you don't need this, but here's an example of how to make a copy with just what you want: newlist = [x for x in mylist if x] Commented Jun 26, 2014 at 6:21

2 Answers 2

6

Unless I'm misunderstanding your specifications, you don't need a regex here. You can just use the string's split method.

>>> mystr = 'This is \n my awesome \nstring'
>>> mystr.split()
['This', 'is', 'my', 'awesome', 'string']
answered Jun 26, 2014 at 5:35

Comments

0

This is what I did to split a white space separated string into list:

re.split(r'\s*', re.sub(r'^\s+|\s*$', '', input_string))

Another problem with your code is that, you should not use str as a variable name, because str is a built in function.

answered Jun 26, 2014 at 5:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.