0

I want to remove some of the selected whitespace in a string. Lets say I have a index of whitespace to remove:

w_index = [1,3]

And a string:

str = 'a b c d'

What I need is to remove first and third whitespaces so the end result is:

str = 'ab cd' 

Thank you.

1
  • 1
    Remember: strings are immutable in python. Commented Sep 14, 2018 at 6:57

3 Answers 3

3
# Input
w_index = [1,3]
str = 'a b c d'

# Solution
space_pos = [p for p in range(len(str)) if str[p]==' ']
w_pos = [space_pos[x-1] for x in w_index]
''.join(str[x+1:y] for x,y in zip([-1]+w_pos, w_pos+[len(str)]))

# result: 'ab cd'
Sign up to request clarification or add additional context in comments.

Comments

1

Python indexing starts from zero so I adjusted your w_index list.

w_index = [0,2]

Also, str is a special name in Python so I renamed your string variable.

string = 'a b c d'

Now create a new list wpos that gives the position of each whitespace in string.

wpos = [i for (i, char) in enumerate(str) if char == ' ']

print "wpos:", wpos

Output:

>> wpos: [1, 3, 5]

We can then loop through w_index in reverse and remove the whitespace by it's position. We can't pop() a string like we can a list, so split the string in two and combine it back together to make a new string.

for i in w_index[::-1]:
    pos = wpos[i]
    string = string[:pos] + string[(pos+1):]
print string

Output:

>> ab cd

2 Comments

Note: this solution is much slower than my solution, especially for large strings. It took 0.47 s for my script to remove 250,000 spaces from a 1,000,000 characters string, while it took your script 101 s to do the same task. More than 200 times slower! This is because your script creates two large strings in a cycle, which is unnecessary.
Yes of course it is slower. If you have large strings to work on, your method is faster. My answer is easier for a beginner to understand with intermediate steps to explain what is happening.
1

You can't change a string in python. What you have to do is create a new string and concatenate the substrings. You loop over the index array and create a substring from the start to the first index (exclusive), the first+1 to the second and so on. At the end you combine the strings.

Comments

Your Answer

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.