如何从Python字符串中删除最后一个字符?
Python支持负索引切片和正切片。负索引从 -1 到-(iterable_length)开始。我们将使用负切片从可迭代对象的末尾获取元素。
索引 -1 从迭代器中获取最后一个元素。
索引-2 从迭代器中获取倒数第二个元素。
它一直持续到第一个元素。
让我们来看一个例子。
name = 'Geekflare'
print(name[-1])
print(name[-len(name)])复制
上面的程序将使用负索引从字符串中打印最后一个字符和第一个字符。
我们如何使用切片从字符串中删除最后一个元素 ?这只是一行代码。我们知道如何使用切片来提取字符串的一部分。让我们将相同的东西与负索引一起应用,以从字符串中删除最后一个字符。
将字符串从开头切到最后一个before元素。
buggy_name = 'GeekflareE'
name = buggy_name[:-1]
print(name)复制
让我们关注上面代码中的第二行。这就是代码中的魔力所在。作为传统切片,它从起始索引提取到最后一个子字符串,但由于切片会忽略给定的第二个索引元素,因此它是一个子切片。
Geekflare如果运行上面的代码,您将获得 输出。
字符串方法 rstrip 从指定给它的字符串的右侧删除字符。因此,我们可以使用它删除字符串的最后一个元素。我们不必编写多行代码即可从字符串中删除最后一个字符。
将最后一个元素赋予 strip 方法,它将通过删除最后一个字符来返回字符串。
让我们看看代码片段。
buggy_name = 'GeekflareE'
name = buggy_name.rstrip(buggy_name[-1])
print(name)复制
我们已经将字符串的最后一个字符赋予了 strip 方法。它从字符串中删除最后一个字符,并返回不包含最后一个字符的副本。
Geekflare如果执行,它将在控制台中打印 。
实际示例–删除最后一个字
是的,我们将在一个实际示例中应用前面几节中的内容。
假设我们有一个包含多行文本的文件。我们需要从文件的每一行中删除最后一个单词。
请按照以下步骤编写程序。
创建一个名为random_text.txt 的文件, 并在其中分几行文本。
将数据变量初始化为空字符串。
在读写模式下使用with 和 open 方法打开文件 。
使用readlines方法读取文件的内容。
遍历内容的每一行。
使用字词split方法分割 文本行。
使用上述方法之一删除最后一个单词。
连接结果以形成字符串。
将结果追加到数据变量。
使用seek 和 truncate 方法从文件中删除数据 。
使用write方法将最新数据写入 文件 。
该文件包含以下数据。
This is a sample line for testing. LastWord.
This is a sample line for testing. KillingIt.
This is a sample line for testing. RandomWord.
This is a sample line for testing. DeleteIt.
This is a sample line for testing. RemovingIt.复制
请参见下面的代码。
updated_data = ''
# opening the file
with open('random_text.txt', 'r+') as file:
# read the file content
file_content = file.readlines()
# iterate over the content
for line in file_content:
# removing last word
updated_line = ' '.join(line.split(' ')[:-1])
# appending data to the variable
updated_data += f'{updated_line}\n'
# removing the old data
file.seek(0)
file.truncate()
# writing the new data
file.write(updated_data)复制
如果使用给定文件执行上述代码,则该文件将具有以下更新的数据。
This is a sample line for testing.
This is a sample line for testing.
This is a sample line for testing.
This is a sample line for testing.
This is a sample line for testing.