如何使用splice删除字符串的最后一个字符

时间:2018-03-03 06:50:31

标签: python python-3.x

比方说我有单词词典, 我如何编码以便它产生

dictionar
dictiona
diction
dictio
dicti
dict
dic
di
d

(删除最后一个字符)

我目前有:

def generate_letter_removed(word):
    return_list4 = []
    for i in range(1, len(word)):
        q = word[:-1]
        return_list4.append(q)
    return return_list4

letter_removed = generate_letter_removed(word)
print(letter_removed)

但这会产生“dictionar”

2 个答案:

答案 0 :(得分:1)

使用字符串切片:

word = "dictionary"
for i in range(len(word), 0, -1):
    print(word[:i])

输出:

dictionary
dictionar
dictiona
diction
dictio
dicti
dict
dic
di
d

作为一项功能:

def slice_output(w):
    print('\n'.join(w[:i] for i in range(len(w), 0, -1)))

答案 1 :(得分:0)

更正了您的代码

def generate_letter_removed(word):
    return_list4 = [word]
    for i in range(1, len(word)):
        q = word[:-i]
        return_list4.append(q)
    return return_list4
word=input("Enter A Word: ")
letter_removed = generate_letter_removed(word)
print(letter_removed)
  

输出

Enter A Word: Dictionary
['Dictionary', 'Dictionar', 'Dictiona', 'Diction', 'Dictio', 'Dicti', 'Dict', 'Dic', 'Di', 'D']