简体   繁体   中英

Python: Remove selected whitespace from string

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.

# 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'

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM