编写一个给定短语的函数,并返回如果我们使用
从输入短语中取出第一个单词。例如,给定“快速褐狐”,您的函数应该返回“快速褐狐”--这是我的代码:
def whatistheremainder(v):
remainderforone = v.split(' ', 1)
outcome = remainderforone[1:]
return outcome我没有得到像“快棕色狐狸”这样的合理输出,而是得到了这样的结果:
['quick brown fox']请帮帮忙
发布于 2021-01-26 11:15:00
这就是你想要得到的吗
def whatistheremainder(v):
remainderforone = v.split(' ', 1)
outcome = remainderforone[1:][0]
return outcome
print(whatistheremainder('the quick brown fox'))输出
quick brown fox发布于 2021-01-26 11:13:17
[1:]从列表中获取一个片段,它本身就是一个列表:
>>> remainderforone
['the', 'quick brown fox']
>>> remainderforone[1:]
['quick brown fox']在这里,片表示法[1:]表示将从索引1(第二项)到列表末尾的所有内容进行切片。列表中只有两个项,因此您可以得到一个大小为一个的列表,因为第一个项被跳过了。
要修复,只需提取列表中的单个元素。我们知道列表应该包含两个元素,所以您想要第二个项目,所以只需使用索引1:
>>> remainderforone[1]
'quick brown fox'作为一种更通用的解决方案,您可能需要考虑使用str.partition()
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'发布于 2021-01-26 11:13:36
您的逻辑可以在一行中进一步简化,方法是将maxsplit参数设置为str.split()函数的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 param来使用第一个解决方案,但是可以使用列表切片而不是索引将其作为列表访问,然后将其加入回:
>>> ''.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'https://stackoverflow.com/questions/65900099
复制相似问题