从字符串中删除最后一个字符 [英] Remove final character from string

查看:63
本文介绍了从字符串中删除最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的字符串长度为 10 个字符.

Let's say my string is 10 characters long.

如何删除最后一个字符?

How do I remove the last character?

如果我的字符串是 "abcdefghij"(我不想替换 'j' 字符,因为我的字符串可能包含多个 'j' 字符)我只希望最后一个字符消失.无论它是什么或出现多少次,我都需要从我的字符串中删除最后一个字符.

If my string is "abcdefghij" (I do not want to replace the 'j' character, since my string may contain multiple 'j' characters) I only want the last character gone. Regardless of what it is or how many times it occurs, I need to remove the last character from my string.

推荐答案

简单:

my_str =  "abcdefghij"
my_str = my_str[:-1]

试试下面的代码片段,通过将字符串转换为列表来更好地理解它是如何工作的:

Try the following code snippet to better understand how it works by casting the string as a list:

str1 = "abcdefghij"
list1 = list(str1)
print(list1)
list2 = list1[:-1]
print(list2)

如果您想接受来自用户的字符串:

In case, you want to accept the string from the user:

str1 = input("Enter :")
list1 = list(str1)
print(list1)
list2 = list1[:-1]
print(list2)

为了去掉句子中的最后一个单词(单词之间用空格等空格隔开):

To make it take away the last word from a sentence (with words separated by whitespace like space):

str1 = input("Enter :")
list1 = str1.split()
print(list1)
list2 = list1[:-1]
print(list2)

这篇关于从字符串中删除最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆