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

I_d*_*hon 3 python python-3.x

我希望在创建一个迭代字符串并将每个字符与删除线字符(\ 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)
Run Code Online (Sandbox Code Playgroud)

到目前为止,我只能连接而不是结合.

roi*_*ppi 11

怎么样:

from itertools import repeat, chain

''.join(chain.from_iterable(zip(text, repeat('\u0336'))))
Run Code Online (Sandbox Code Playgroud)

甚至更简单,

'\u0336'.join(text) + '\u0336'
Run Code Online (Sandbox Code Playgroud)


pdw*_*pdw 7

def strike(text):
    result = ''
    for c in text:
        result = result + c + '\u0336'
    return result
Run Code Online (Sandbox Code Playgroud)

很酷的效果.


mha*_*wke 5

已编辑

\n\n

正如roippi所指出的,到目前为止,其他答案实际上是正确的,而下面这个是错误的。把它留在这里,以防其他人有和我一样的错误想法。

\n\n
\n\n

到目前为止,其他答案都是错误的 - 它们没有删除字符串的第一个字符。试试这个:

\n\n
def strike(text):\n    return \'\'.join([u\'\\u0336{}\'.format(c) for c in text])\n\n>>> print(strike(\'this should do the trick\'))\n\'\xcc\xb6t\xcc\xb6h\xcc\xb6i\xcc\xb6s\xcc\xb6 \xcc\xb6s\xcc\xb6h\xcc\xb6o\xcc\xb6u\xcc\xb6l\xcc\xb6d\xcc\xb6 \xcc\xb6d\xcc\xb6o\xcc\xb6 \xcc\xb6t\xcc\xb6h\xcc\xb6e\xcc\xb6 \xcc\xb6t\xcc\xb6r\xcc\xb6i\xcc\xb6c\xcc\xb6k\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

这适用于 Python 2 和 Python 3。

\n