1

I am trying to split strings, which are separated by a variable number of spaces.

something like this:

abcde          123456

I know how to trim a string, but I am having hard time here, because the 2 strings has a variable amount of spaces. If a string is long, it will have less spaces in between, so I can't find a way to delimit them clearly, so I can save each of them in a different string.

How do you actually do so?

3 Answers 3

2

Use .split():

input = 'abcde          123456'
output = input.split()
print(output)

['abcde', '123456']

Sign up to request clarification or add additional context in comments.

3 Comments

why not just input.split() without any arguments?
@AnandSKumar "Explicit is better than implicit." =)
not when you are unneccessarily increasing amount of code. And who said its implicit? Its clearly defined in the documentation that .split() without argument would split based on all whitespaces - docs.python.org/2/library/stdtypes.html#str.split
0

Python string's have a method called split() just for this case. When called on a string with no arguments, it will split on space and strip out any number of leading and trailing spaces:

data = 'abcde          123456'
letters, numbers = data.split()

2 Comments

Why do you need strip() if you are using split() without arguments, it would already have no leading or trailing spaces.
I agree with @AnandSKumar, I think you don't need strip() after using split()
-1

Its the best way to remove the spaces before splitting:

import re
my_string = "abcde          123456"
regex = re.compile(r'( [ ]+)')
shortend_string = regex.sub(' ', a)
elements = shortend_string.split(' ') 

4 Comments

What is the advantage of regex + split, versus using directly strip?
@newbiez: There is no advantage. Just call split without any parameter and you're good to go.
regex is overhead here
The regex will handle all spaces with only one replacement.

Your Answer

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