简体   繁体   English

Python:从字符串中删除选定的空格

[英]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. 您无法在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. 你的索引阵列上循环,并创建从一开始的子串的第一个索引(不包括),第一+ 1至第二等等。 At the end you combine the strings. 在最后你结合的字符串。

Python indexing starts from zero so I adjusted your w_index list. Python索引从零开始,因此我调整了w_index列表。

w_index = [0,2]

Also, str is a special name in Python so I renamed your string variable. 另外, str是Python中的特殊名称,因此我重命名了您的字符串变量。

string = 'a b c d'

Now create a new list wpos that gives the position of each whitespace in string . 现在创建一个新列表wpos ,它给出每个空白在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. 然后,我们可以反向遍历w_index并通过其位置删除空格。 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. 我们无法像列表一样pop()字符串,因此请将字符串一分为二,然后将其重新组合在一起以创建新字符串。

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

Output: 输出:

>> ab cd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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