geekdoc-python-zh/docs/py4b/python-split.md

57 lines
1.9 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 如何在 Python 中使用 Split
> 原文:<https://www.pythonforbeginners.com/dictionary/python-split>
了解如何在 python 中使用 split。
## 定义
split()方法使用用户指定的分隔符将一个字符串拆分成一个列表。如果没有定义分隔符,则使用空白(" ")。
## 为什么要使用 Split()函数?
在某些时候,你可能需要把一个大的字符串分解成更小的块,或者字符串。这与将字符串合并或组合成一个字符串的串联相反。
为此,您可以使用 python split 函数。它所做的是分割或分解字符串,并使用定义的分隔符将数据添加到字符串数组中。
如果在调用函数时没有定义分隔符,默认情况下将使用空格。更简单地说,分隔符是一个定义好的字符,它将放在每个变量之间。
### Python Split 函数的应用示例
让我们来看一些例子。
```py
*x* *= **blue,red**,green***
*x.**split**(**,)*
*[blue, red, green]*
*>>>*
*>>>* *a,b**,c* *=* *x.split**(,)*
*>>> a*
*blue*
*>>> b* 
*red*
*>>> c*
*green*
```
从这段代码中可以看出该函数将包含三种颜色的原始字符串进行分割然后将每个变量存储在一个单独的字符串中。这给我们留下了三串“a”、“b”和“c”。然后当你要求解释器吐出存储在这些字符串中的变量时你会得到适当的颜色。
很整洁,不是吗?当您大量使用字符串和变量时,它也非常有用。
让我们看另一个例子。
```py
*>>> words = This is random text were going to split apart*
*>>> words2 =* *words.split**( )*
*>>> words2*
*[This, is, random, text, were, going, to, split, apart]*
```
我们在这里所做的是分割较大的字符串并将变量作为一个列表存储在“words2”字符串下。