简体   繁体   English

Python:为什么 str.split() 返回一个列表而 str.partition() 返回一个元组?

[英]Python: Why Does str.split() Return a list While str.partition() Returns a tuple?

Comparing Python's str.split() with str.partition() , I see that they not only have different functions ( split() tokenizes the whole string at each occurrence of the delimiter, while partition() just returns everything before and everything after the first delimiter occurrence), but that they also have different return types.将 Python 的str.split()str.partition() ,我发现它们不仅具有不同的功能( split()在每次出现分隔符时标记整个字符串,而partition()只返回之前的所有内容和之后的所有内容第一个分隔符出现),但它们也有不同的返回类型。 That is, str.split() returns a list while str.partition() returns a tuple .也就是说, str.split()返回一个liststr.partition()返回一个tuple This is significant since a list is mutable while a tuple is not.这很重要,因为list是可变的,而tuple则不是。 Is there any deliberate reason behind this choice in the API design, or is it "just the way things are."在 API 设计中,这种选择背后是否有任何故意的原因,还是“事情就是这样”。 I am curious.我好奇。

The key difference between those methods is that split() returns a variable number of results, and partition() returns a fixed number.这些方法之间的主要区别在于split()返回可变数量的结果,而partition()返回固定数量。 Tuples are usually not used for APIs which return a variable number of items.元组通常不用于返回可变数量项目的 API。

@yole answer summarise the reasoning why partition() returns tuple. @yole 回答总结了partition()返回元组的原因。 But there is a nice way to "exploit" that fact.但是有一个很好的方法来“利用”这个事实。 I found below example in "Automate the boring stuff with Python".我在“用 Python 自动化无聊的东西”中找到了下面的例子。

   before, sep, after = 'Hello, world!'.partition(' ')
   print(before)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM