繁体   English   中英

python - 删除与字符串中数字对应的多个字符

[英]python - remove a number of characters corresponding to the digit in string

我正在尝试编写一个函数,该函数返回一个类似于消耗的字符串 s 的字符串,但是每次 s 中出现一个数字时,都应从字符串中删除与该数字对应的多个字符,包括数字本身. 如果删除一个数字的子串会删除另一个数字,则不应考虑第二个数字。 例如:

cleanstr("23apple") -> "apple"
cleanstr("100") -> "00"
cleanstr("6Hello") -> ""
cleanstr("0 red 37 blue") -> "0 red blue"

当字符串中有连续数字时,我的代码不会返回预期的结果。 例如,cleanstr("01234560") 返回 "0260" 而不是 "0"。 所以我知道我的循环中的问题是在检查“0”和“1”之后它跳过“2”并移动到“3”。 有人可以帮我解决问题吗?

def cleanstr(s):
    i = 0
    lst = list(s)
    while i < len(lst):
        if lst[i].isdigit():
            lst = lst[0:i] + lst[i+int(lst[i]):]
        i = i + 1
    return ''.join(lst)

似乎更容易将此视为附加当前字符或在每次迭代中按i推进计数器:

def cleanstr(s):
    i = 0
    res = ''
    while i < len(s):
        if s[i].isdigit() and int(s[i]) > 0:
            i += int(s[i])
        else:
            res += s[i]
            i += 1
    return res

cleanstr("0 red 37 blue")
# '0 red blue'

cleanstr("23apple") 
# 'apple'

cleanstr("01234560") 
# '0'

您可以从字符串创建一个迭代器来遍历字符,并仅在字符不是 1 到 9 之间的数字时才输出该字符,或者使用itertools.islice从迭代器中消耗给定数量的字符减 1:

from itertools import islice
def cleanstr(s):
    i = iter(s)
    return ''.join(c for c in i if not '0' < c <= '9' or not (tuple(islice(i, int(c) - 1)),))
TESTED = ["23apple", "100", "6Hello", "0 red 37 blue"]

def cleanstr(s):
    i = 0
    while i<len(s):
        n = ord(s[i]) - ord('0')
        if n>=0 and n<=9:
            s = s[:i] + s[i+n:]
            i = i + n
        i = i + 1
    return s

for str in TESTED:
    print(cleanstr(str))

正则表达式?

>>> for s in "23apple", "100", "6Hello", "0 red 37 blue", "01234560":
        t = re.sub('|'.join(f'{i+1}.{{{i}}}' for i in range(9)), '', s)
        print([s, t])

['23apple', 'apple']
['100', '00']
['6Hello', '']
['0 red 37 blue', '0 red blue']
['01234560', '0']

构建的表达式为1.{0}|2.{1}|3.{2}|4.{3}|5.{4}|6.{5}|7.{6}|8.{7}|9.{8} .

暂无
暂无

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

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