我想洗掉連續的“a”子字串并用字串中的一個“a”替換它們而不匯入任何包。例如,我想abbccca從aaabbcccaaaa. 有什么建議么?謝謝。
uj5u.com熱心網友回復:
此方法將從您的字串中洗掉確定的重復字符:
def remove_dulicated_char(string, char):
new_s = ""
prev = ""
for c in string:
if len(new_s) == 0:
new_s = c
prev = c
if c == prev and c == char:
continue
else:
new_s = c
prev = c
return new_s
print(remove_dulicated_char("aaabbcccaaaa", "a"))
uj5u.com熱心網友回復:
使用回圈有什么問題?
oldstring = 'aaabbcccaaaa'
# Initialise the first character as the same as the initial string
# as this will always be the same.
newstring = oldstring[0]
# Loop through each character starting at the second character
# check if the preceding character is an a, if it isn't add it to
# the new string. If it is an a then check if the current character
# is an a too. If the current character isn't an a then add it to
# the new string.
for i in range(1, len(oldstring)):
if oldstring[i-1] != 'a':
newstring = oldstring[i]
else:
if oldstring[i] != 'a':
newstring = oldstring[i]
print(newstring)
uj5u.com熱心網友回復:
使用python正則運算式就可以了。如果您不了解正則運算式。它們對于這種匹配非常強大
重新進口
str = 'aaabbcccaaaa'
print(re.sub('a ', 'a', str))
uj5u.com熱心網友回復:
您可以使用一個函式以遞回方式洗掉字串出現的雙值,直到只保留一個重復字串的出現:
val = 'aaabbcccaaaaaaaaaaa'
def remove_doubles(v):
v = v.replace('aa', 'a')
if 'aa' in v:
v = remove_doubles(v)
if 'aa' in v:
v = remove_doubles(v)
else: return v
else: return v
print(remove_doubles(val))
uj5u.com熱心網友回復:
有很多方法可以做到這一點。這是另一個:
def remove_duplicates(s, x):
t = [s[0]]
for c in s[1:]:
if c != x or t[-1] != x:
t.append(c)
return ''.join(t)
print(remove_duplicates('aaabbcccaaaa', 'a'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473900.html
下一篇:用逗號分隔的引號連接字串
