Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.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,预期结果是123_香蕉_胡萝卜,因为上面的代码已正确生成 上面的代码运行得很好,但我的问题是:是否有直接、简单、快捷的方法可以获得相同的结果 这可能不需要使用“u”。join,但不限于这可能是一种解决方案 >>> s = 'apple_123_banana_carrot_dog_eggs_567' >>> '_'.join(s.split('_')[1:4]) '123_banana_carrot' 我仍然不清楚你想要得到什么结果。您是否总是使用相同的字符串

预期结果是123_香蕉_胡萝卜,因为上面的代码已正确生成

上面的代码运行得很好,但我的问题是:是否有直接、简单、快捷的方法可以获得相同的结果


这可能不需要使用“u”。join,但不限于

这可能是一种解决方案

>>> s = 'apple_123_banana_carrot_dog_eggs_567'
>>> '_'.join(s.split('_')[1:4])
'123_banana_carrot'

我仍然不清楚你想要得到什么结果。您是否总是使用相同的字符串作为输入,并希望得到相同的结果?你还会有其他字符串作为输入吗?其他弦呢?他们的预期产出是多少?@Lysandos Nikolaou你是怎么数到这么多数字的?继续数数。。。
s =  'apple_123_banana_carrot_dog_eggs_567'
p = s.rsplit('_',3)[0]
print(p)