从句子中删除第一个单词并返回剩余的字符串

2024-03-28 16:56:14 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个给定词组的函数,并返回我们获取的词组
从输入短语中找出第一个单词。 例如,给定'quick brown fox',函数应返回'quick brown fox' 这是我的代码:

def whatistheremainder(v):
    remainderforone = v.split(' ', 1)
    outcome = remainderforone[1:]
    return outcome

而不是获得合理的输出,如: “敏捷的棕色狐狸” 我得到的是这样的东西:

['quick brown fox']

请帮忙


Tags: 函数代码returndefquick单词split棕色
3条回答

[1:]从列表中获取一个切片,它本身就是一个列表:

>>> remainderforone
['the', 'quick brown fox']
>>> remainderforone[1:]
['quick brown fox']

这里的切片表示法[1:]表示从索引1(第二项)到列表末尾的所有内容都要切片。列表中只有两项,因此您会得到一个大小为1的列表,因为第一项被跳过

要修复此问题,只需提取列表中的单个元素。我们知道列表应该包含2个元素,所以您需要第二项,所以只需使用索引1:

>>> remainderforone[1]
'quick brown fox'

作为一个更一般的解决方案,您可能需要考虑使用{a1}:

for s in ['the quick brown fox', 'hi there', 'single', '', 'abc\tefg']:
    first, sep, rest = s.partition(' ')
    first, sep, rest

('the', ' ', 'quick brown fox')
('hi', ' ', 'there')
('single', '', '')
('', '', '')
('abc\tefg', '', '')

根据您希望如何处理没有发生分区的情况,您可以返回rest,或者可能返回first

def whatistheremainder(v):
    first, sep, rest = v.partition(' ')
    return rest

for s in ['the quick brown fox', 'hi there', 'single', '', 'abc\tefg']:
    whatistheremainder(s)

'quick brown fox'
'there'
''
''
''

或者,您可以争辩说,如果没有分区发生,那么应该返回原始字符串,因为没有要删除的第一个字。如果未发生分区,则可以使用以下事实:sep将是空字符串:

def whatistheremainder(v):
    first, sep, rest = v.partition(' ')
    return rest if sep else first

for s in ['the quick brown fox', 'hi there', 'single', '', 'abc\tefg']:
    whatistheremainder(s)

'quick brown fox'
'there'
'single'
''
'abc\tefg'

通过将^{}函数的maxsplit参数设置为1,您的逻辑可以进一步简化为一行:

>>> my_string = 'the quick brown fox'

>>> my_string.split(' ', 1)[1]
'quick brown fox'

如果字符串包含一个单词或没有单词,则会引发IndexError

另一种替代方法使用字符串切片list.index(...)如下:

>>> my_string[my_string.index(' ')+1:]
'quick brown fox'

与前面的解决方案类似,此解决方案也不适用于一个或没有单词字符串,并将引发ValueError异常

要处理只有一个字或没有字的字符串,您可以使用maxsplit参数使用第一种解决方案,但使用列表切片而不是索引将其作为列表访问,并将其重新连接:

>>> ''.join(my_string.split(' ', 1)[1:])
'quick brown fox'

代码的问题是需要加入使用' '.join(outcome)发送回的字符串列表。因此,您的功能将变为:

def whatistheremainder(v):
    remainderforone = v.split(' ', 1)
    outcome = remainderforone[1:]
    return ' '.join(outcome)

样本运行:

>>> whatistheremainder('the quick brown fox')
'quick brown fox'

您可以使用上述逻辑将字符串拆分为单词并将其连接回跳过第一个单词也可以转换为一行,如下所示:

>>> ' '.join(my_string.split()[1:])
'quick brown fox'

这就是你想要的吗

def whatistheremainder(v):
    remainderforone = v.split(' ', 1)
    outcome = remainderforone[1:][0]
    return outcome
print(whatistheremainder('the quick brown fox'))

输出

quick brown fox

相关问题 更多 >