如果您能帮助我创建一个迭代字符串并将每个字符与删除线字符 (\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)
到目前为止,我只能连接而不是组合。
def strike(text):
result = ''
for c in text:
result = result + c + '\u0336'
return result
效果很酷。
怎么样:
from itertools import repeat, chain
''.join(chain.from_iterable(zip(text, repeat('\u0336'))))
或者更简单地说,
'\u0336'.join(text) + '\u0336'
已编辑
正如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。
虽然
'\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()
如果您想在删除线中包含空格,则必须将普通空格替换为不间断空格:
def strikethrough(mytext):
''' replacing space with 'non-break space' and striking through'''
return("\u0336".join(mytext.replace(" ","\u00a0"))+ "\u0336")
如果输出用于终端,也可以通过插入 ANSI 转义码来更改终端设置。
因此,您基本上可以使用删除线(“[9m”)的转义序列或转义序列覆盖的任何文本样式包围要更改的文本。最后的“0m”代码是重置终端样式:
text_strike = "strikethrough"
text_nostrike = "no strikethrough"
print(f"{text_nostrike} \033[9m{text_strike}\033[0m {text_nostrike}")
转义码列表: https://gist.github.com/ConnerWill/d4b6c776b509add763e17f9f113fd25b
我从这个问题的答案中得到了这个想法,它用于改变颜色: 如何用颜色显示两个字符串序列的差异?