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



编写一个函数,给定一个短语,并返回从输入短语中取出
第一个单词后得到的短语。例如,给定' the quick brown fox ',你的函数应该返回' quick brown fox '这是我的代码:

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

而不是得到一个合理的输出:"敏捷的棕色狐狸"我得到这样的内容:

['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

您的逻辑可以进一步简化为一行,将maxsplit参数设置为1,str.split()函数为:

>>> 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'

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

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

这里的切片符号[1:]表示将从索引1(第二项)到列表末尾的所有内容切片。列表中只有两个元素,所以你得到一个大小为1的列表,因为第一个元素被跳过了。

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

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

作为更通用的解决方案,您可能需要考虑使用str.partition():

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

根据你想如何处理那些没有发生分区的情况,你可以只返回rest,或者可能是first:

def whatistheremainder(v):
first, sep, rest = v.partition(' ')
return rest
for s in ['the quick brown fox', 'hi there', 'single', '', 'abctefg']:
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', '', 'abctefg']:
whatistheremainder(s)
'quick brown fox'
'there'
'single'
''
'abctefg'
def whatistheremainder(v):
remainderforone = v.split(' ', 1)
outcome=v if len(remainderforone)== 1 else ''.join(remainderforone[1:])
return outcome

这一行'outcome=v if len(remainderforone)== 1 else " .join(remainderforone[1:])'检查列表的长度是否包含所有的单词如果长度等于1,则表示只有一个单词,因此结果将等于v(输入的单词)否则表示有多个单词结果将等于输入的字符串,但不包含第一个单词

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

最新更新