簡體   English   中英

從字符串中刪除最后一個字符

[英]Remove final character from string

如何從字符串中刪除最后一個字符?

"abcdefghij"  →  "abcdefghi"

簡單的:

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

試試下面的代碼片段,通過將字符串轉換為列表來更好地理解它是如何工作的:

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

如果您想接受來自用戶的字符串:

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

為了使它從句子中刪除最后一個單詞(單詞用空格等空格分隔):

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

您要做的是在 Python 中擴展字符串切片

假設所有字符串的長度為 10,最后一個字符被刪除:

>>> st[:9]
'abcdefghi'

刪除最后N字符:

>>> N = 3
>>> st[:-N]
'abcdefg'

對您來說最簡單的解決方案是使用字符串切片

蟒蛇 2/3:

source[0: -1]  # gets all string but not last char

蟒蛇2:

source = 'ABC'    
result = "{}{}".format({source[0: -1], 'D')
print(result)  # ABD

蟒蛇3:

source = 'ABC'    
result = f"{source[0: -1]}D"
print(result)  # ABD

使用切片,可以指定startstop索引以提取字符串s一部分。 格式為s[start:stop] 但是,默認情況下start = 0 所以,我們只需要指定stop


使用stop = 3

>>> s = "abcd"
>>> s[:3]
'abc'

使用stop = -1從末尾刪除1字符(最佳方法):

>>> s = "abcd"
>>> s[:-1]
'abc'

使用stop = len(s) - 1

>>> s = "abcd"
>>> s[:len(s) - 1]
'abc'

所以有一個名為rstrip()的 function 用於此類內容。 您輸入要刪除的值,在本例中是最后一個元素,即字符串 [-1]:

string = "AbCdEf" 
newString = string.rstrip(string[-1])
print(newString)

如果您運行他的代碼,您會看到“f”值已被刪除。

OUTPUT: AbCdE
def RemoveLastOne(text): # RemoveLastOne function
    text = str(text) # convert type to str
    result = text[:(len(text)-1)] # remove last string
    return result #return result without last string

text = 'abcdefghij' #varible
result = RemoveLastOne(text) #input --> abcdefghij

print(result) #output --> abcdefghi

這實際上應該有效:

string = string[0:len(string) - 2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM