Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-根据词尾列表删除单词的词尾_Python - Fatal编程技术网

Python-根据词尾列表删除单词的词尾

Python-根据词尾列表删除单词的词尾,python,Python,如果单词的结尾与给定列表中任何可能的结尾相似,我想删除单词的结尾。我使用了以下代码: ending = ('os','o','as','a') def rchop(thestring): if thestring.endswith((ending)): return thestring[:-len((ending))] return thestring rchop('potatos') 结果是:“锅”。 但我想要这个:“波塔特” 我怎样才能解决这个问题 谢谢您当时正在按结尾

如果单词的结尾与给定列表中任何可能的结尾相似,我想删除单词的结尾。我使用了以下代码:

ending = ('os','o','as','a')

def rchop(thestring):
  if thestring.endswith((ending)):
    return thestring[:-len((ending))]
  return thestring

rchop('potatos')
结果是:“锅”。 但我想要这个:“波塔特”

我怎样才能解决这个问题


谢谢

您当时正在按结尾元组的长度(4个元素)对字符串进行切片。这就是你收到错误字符串的原因

endings = ('os','o','as','a')

def rchop(thestring):
    for ending in endings:
        if thestring.endswith(ending):
            return thestring[:-len(ending)]
    return thestring

print(rchop('potatos'))
返回:

potat

您正在按结尾元组的长度(4个元素)对字符串进行切片。这就是你收到错误字符串的原因

endings = ('os','o','as','a')

def rchop(thestring):
    for ending in endings:
        if thestring.endswith(ending):
            return thestring[:-len(ending)]
    return thestring

print(rchop('potatos'))
返回:

potat

您可以尝试使用
re

import re
x="potatos"
print re.sub(r"(?:os|as|a|o)$","",x)
输出:
potat


|
在这里表示
$
表示
字符串结尾
您可以尝试
re

import re
x="potatos"
print re.sub(r"(?:os|as|a|o)$","",x)
输出:
potat

|
在这里表示
,而
$
表示
字符串结尾
,或尝试此方法(非常短),(注意,当
结尾
元素中的非元素位于字符串结尾时,甚至可以使用此方法):

现在:

是:

果然如此

或尝试此方法(非常短),(注意,即使在字符串末尾没有
结束
元素时也有效):

现在:

是:


果然如此

你比我快你比我快