Skip to main content
 首页 » 编程设计

python之替换字符串中的子字符串

2025年05月04日30zhoujg

我的函数在字符串 hex 符号(十六进制 CSS 颜色)中找到并替换为短符号。
例如:#000000可以表示为#000

import re 
 
def to_short_hex (string): 
    match = re.findall(r'#[\w\d]{6}\b', string) 
 
    for i in match: 
        if not re.findall(r'#' + i[1] + '{6}', i): 
            match.pop(match.index(i)) 
 
    for i in match: 
        string = string.replace(i, i[:-3]) 
 
    return string; 
 
to_short_hex('text #FFFFFF text #000000 #08088') 

出局:

text #FFF text #000 #08088 

有什么方法可以使用 list comprehension 等来优化我的代码吗?

请您参考如下方法:

这个怎么样?您可以通过将 is6hexdigit 嵌入 to_short_hex 来加快它的速度,但我希望它更具可读性。

hexdigits = "0123456789abcdef" 
 
def is6hexdigit(sub): 
    l = sub.lower() 
    return (l[0] in hexdigits) and (l.count(l[0]) == 6) 
 
def to_short_hex(may_have_hexes): 
    replaced = ((sub[3:] if is6hexdigit(sub[:6]) else sub) 
                        for sub in may_have_hexes.split('#')) 
    return '#'.join(replaced)