Python:创建删除线字符串类型

16 投票
5 回答
25908 浏览
提问于 2025-04-18 16:50

我希望能得到一些帮助,创建一个函数,能够遍历一个字符串,把每个字符和一个删除线字符(\u0336)结合起来。最终的输出应该是原字符串的删除线版本。就像这样。

大概是这样的。

def strike(text):
    i = 0
    new_text = ''
    while i < len(text):
        new_text = new_text + (text[i] + u'\u0336')
        i = i + 1
    return(new_text)

到目前为止,我只能把字符连接在一起,而不是结合在一起。

5 个回答

0

如果你想在删除线中包含空格,你需要把普通的空格换成不换行的空格:

def strikethrough(mytext):
    ''' replacing space with 'non-break space' and striking through'''
    return("\u0336".join(mytext.replace(" ","\u00a0"))+ "\u0336")
1

虽然 '\u0336' 可以解决一些问题,但在不同语言的情况下可能就不太管用了。

比如说:我是誰 → ̶我̶是̶誰。

你可以看到,本来好的文字变成了我们看不懂的奇怪符号。

所以我写了下面的代码:

import tkinter as tk
root = tk.Tk()
root.state('zoomed')

class strikethrough(tk.Frame):
    def __init__(self, frame, text, **options):
        super().__init__(frame)
        c = tk.Canvas(self, **options)
        textId = c.create_text(0, 0, text = text, fill = "#FFFFFF", font = ("", 30, "bold"))
        x1, y1, x2, y2 = c.bbox(textId)
        linewidth = 3
        lineXOffset = 3
        lineId = c.create_line(x1, 0, x2, 0, width=linewidth)
        c.pack(fill="both", expand=1)
        c.bind("<Configure>", lambda event: TextPositionChange(c, textId, lineId, linewidth, lineXOffset))
        self.canvas, self.textId = c, textId


def TextPositionChange(canvas, TextId, LineId, LineWidth, LineXOffset):
    x1, y1, x2, y2 = canvas.bbox(TextId)
    xOffSet, yOffSet = (x2-x1)/2, (y2-y1)/2
    x, y = canvas.winfo_width()/2-xOffSet, canvas.winfo_height()/2-yOffSet #left_top_position
    canvas.moveto(TextId, x, y)
    canvas.moveto(LineId, x-LineXOffset, y+(y2-y1)/2-LineWidth/2)

frame = strikethrough(root, "我是誰", bg="#777777")
frame.place(relx=0.5, rely=0.5, relwidth=0.5, anchor="center")

root.mainloop()
6

编辑过

正如roippi所指出的,之前的其他回答其实是正确的,而下面这个回答是错误的。我把它留在这里,以防其他人也像我一样产生错误的理解。


之前的其他回答是错的——它们没有删除字符串的第一个字符。试试这个:

def strike(text):
    return ''.join([u'\u0336{}'.format(c) for c in text])

>>> print(strike('this should do the trick'))
'̶t̶h̶i̶s̶ ̶s̶h̶o̶u̶l̶d̶ ̶d̶o̶ ̶t̶h̶e̶ ̶t̶r̶i̶c̶k'

这个在Python 2和Python 3中都能用。

16

这样怎么样:

from itertools import repeat, chain

''.join(chain.from_iterable(zip(text, repeat('\u0336'))))

或者更简单一点,

'\u0336'.join(text) + '\u0336'
26
def strike(text):
    result = ''
    for c in text:
        result = result + c + '\u0336'
    return result

这个效果很酷。

撰写回答