[英]How to leave only one defined sub-string in a string in Python
说我有以下字符串之一:
"a b c d e f f g" || "a b c f d e f g"
而且我希望整个字符串中只出现一个子字符串(本例中为f ),以便对其进行某种程度的清理。 每个字符串的结果将是:
"a b c d e f g" || "a b c d e f g"
使用的一个例子是:
str = "a b c d e f g g g g g h i j k l"
str.leaveOne("g")
#// a b c d e f g h i j k l
如果您离开哪个实例都没有关系,则可以使用str.replace
,它带有一个参数,表示要执行的替换次数:
def leave_one_last(source, to_remove):
return source.replace(to_remove, '', source.count(to_remove) - 1)
这将保留最后一次出现。
我们可以通过反转两次字符串来修改它以保留第一次出现的情况:
def leave_one_first(source, to_remove):
return source[::-1].replace(to_remove, '', source.count(to_remove) - 1)[::-1]
但是,这很丑陋,更不用说效率低下了。 一种更优雅的方法可能是:以找到字符的第一个出现的结尾的子字符串,替换其余出现的子字符串,最后将它们串联在一起:
def leave_one_first_v2(source, to_remove):
first_index = source.index(to_remove) + 1
return source[:first_index] + source[first_index:].replace(to_remove, '')
如果我们尝试这样做:
string = "a b c d e f g g g g g h i j k l g"
print(leave_one_last(string, 'g'))
print(leave_one_first(string, 'g'))
print(leave_one_first_v2(string, 'g'))
输出:
a b c d e f h i j k l g
a b c d e f g h i j k l
a b c d e f g h i j k l
如果您不想保留空格,则应使用基于split
的版本:
def leave_one_split(source, to_remove):
chars = source.split()
first_index = chars.index(to_remove) + 1
return ' '.join(chars[:first_index] + [char for char in chars[first_index:] if char != to_remove])
string = "a b c d e f g g g g g h i j k l g"
print(leave_one_split(string, 'g'))
输出:
'a b c d e f g h i j k l'
如果我理解正确,则可以使用正则表达式和re.sub
查找两个或两个以上字母的组(带或不带空格),并将其替换为单个实例:
import re
def leaveOne(s, char):
return re.sub(r'((%s\s?)){2,}' % char, r'\1' , s)
leaveOne("a b c d e f g g g h i j k l", 'g')
# 'a b c d e f g h i j k l'
leaveOne("a b c d e f ggg h i j k l", 'g')
# 'a b c d e f g h i j k l'
leaveOne("a b c d e f g h i j k l", 'g')
# 'a b c d e f g h i j k l'
编辑
如果目标是消除除一个字母之外的所有字母,您仍然可以使用带正则表达式的正则表达式来选择所有字母,然后选择相同的字母:
import re
def leaveOne(s, char):
return re.sub(r'(%s)\s?(?=.*?\1)' % char, '' , s)
print(leaveOne("a b c d e f g g g h i j k l g", 'g'))
# 'a b c d e f h i j k l g'
print(leaveOne("a b c d e f ggg h i j k l gg g", 'g'))
# 'a b c d e f h i j k l g'
print(leaveOne("a b c d e f g h i j k l", 'g'))
# 'a b c d e f g h i j k l'
这甚至应该适用于更复杂的模式,例如:
leaveOne("a b c ffff d e ff g", 'ff')
# 'a b c d e ff g'
给定字符串
mystr = 'defghhabbbczasdvakfafj'
cache = {}
seq = 0
for i in mystr:
if i not in cache:
cache[i] = seq
print (cache[i])
seq+=1
mylist = []
在这里,我用值对字典进行了排序
for key,value in sorted(cache.items(),key=lambda x : x[1]):
mylist.append(key)
print ("".join(mylist))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.