python字符串拆分_在python字符串中拆分vs分区

python字符串拆分

split()与partition()(split() vs. partition())

In Python, we can split the string by using the following methods. Let’s look at these methods in detail.

在Python中,我们可以使用以下方法拆分字符串。 让我们详细看看这些方法。

1. split()
2. rsplit()
3. splitlines()
4. partition()
5. rpartition()
6. re.split()
7. Differences between split() and partition()
8. Conclusion
9. Resources

分裂() (split())

“Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).”

“使用sep作为分隔符字符串,返回字符串中的单词列表。 如果指定了maxsplit,则最多完成maxsplit个分割(因此,列表最多包含maxsplit+1元素)。 如果未指定maxsplit-1 ,则分割数没有限制(已进行所有可能的分割)。”

Python docs

Python文档

str.split(sep=None,maxsplit=-1)

str.split(sep=None,maxsplit=-1)

Return type → List

返回类型→清单

示例1:如果未提及sep (分隔符),它将根据字符串中的空格将字符串拆分(Example 1: If a sep (delimiter) isn’t mentioned, it’ll split the string based on the whitespaces in the string)

a="Hello Python"print (a.split())
#Output:['Hello', 'Python']

示例2:如果提到了sep(分隔符),它将根据分隔符的出现进行拆分 (Example 2: If a sep (delimiter) is mentioned, it’ll split based on the occurrences of the delimiter)

colors='red-green-blue-yellow'print (colors.split("-"))
#Output:['red', 'green', 'blue', 'yellow']

例子3 (Example 3)

a="three times by three makes nine"print (a.split(sep="three"))
#Output:['', ' times by ', ' makes nine']

示例4:提到最大拆分 (Example 4: A maxsplit is mentioned)

If maxsplit is mentioned as 1, it’ll split on the first occurrence only.If maxsplit is given as 2, it’ll split on the first two occurrences only.

如果将maxsplit称为1 ,则仅在第一次出现时拆分;如果将maxsplit设为2 ,则仅在前两个出现时拆分。

colors="red-orange-yellow-purple"print (colors.split("-",maxsplit=1))
#Output:['red', 'orange-yellow-purple']print (colors.split(&#
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值