简体   繁体   English

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

[英]How do I use splice to remove the last character of a string

say for example I have the word dictionary, how do I code so that it produces 例如说我有字典这个词,我该如何编码以便产生

dictionar
dictiona
diction
dictio
dicti
dict
dic
di
d

(every last character is removed) (删除最后一个字符)

I currently have: 我目前有:

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)

but this produces "dictionar" 但这会产生“字典”

Use string slicing: 使用字符串切片:

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

Output: 输出:

dictionary
dictionar
dictiona
diction
dictio
dicti
dict
dic
di
d

As a function: 作为功​​能:

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

Corrected your code 更正了您的代码

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)

Output 产量

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从最后一个“。”之后的字符串中删除最后一个字符 - How do i remove the last character from a string after the last “.” 如何从python中的字符串中删除(真正的)最后一个字符? [即不创建新引用] - How do I remove (for real) the last character from a string in python? [i.e. NOT create a new reference] 如何删除字符串的最后一个字符 - How to remove last character of a string 如何在python中删除RTL字符串的最后一个字符? - How do I remove the last character of an R-T-L string in python? 如何删除Python文本中的最后一个换行符? - How do I remove the last newline character in a text in Python? 我如何使用正则表达式获取两个字符内的字符串并删除该字符串内的某些字符 - how do i use regex to get a string inside two character and remove certain characters inside that string 我怎样才能拼接一个字符串? - How can I splice a string? 如何在数据框列中的字符之后删除字符串的其余部分? - How do I remove the rest of a string after a character in a dataframe column? 如何删除 DataFrame 中字符串中的特殊字符,如“,”? - How do I remove special character like "," within a string in a DataFrame? 如何从字符串[python]中删除一次字符? - How do I remove a character once from a string [python]?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM