Python 字符串拆分

位置:首页>文章>详情   分类: Python教程 > 编程技术   阅读(345)   2024-05-15 10:55:58

Python example to 将字符串拆分为 列表 的标记 using the delimiters such as space, comma, 正则表达式, or multiple delimiters.

1. Python 拆分(分隔符,最大拆分) Syntax

拆分方法的语法是:

string.split(separator, maxsplit)
  • 以上两个参数都是可选的。
  • The 分隔器 is the separator to use for splitting the string. 默认情况下,任何空格(空格、制表符等)都是分隔符。
  • 最大分裂 指定要进行的最大分裂数。默认值为-1,即“所有出现”

2. 默认行为

默认情况下,拆分() 方法将字符串分成无限标记的列表,默认分隔符是任何空格。在以下示例中,字符串在单词之间包含非偶数空格

>>> str = 'how to do in       java'
 
>>> str.split()     # split string using default delimiter and max splits
 
['how', 'to', 'do', 'in', 'java'] #Output

3.逗号分割

在以下示例中,我们使用逗号作为分隔字符串的分隔符。

>>> str = 'how,to,do,in,java'
 
>>> str.split(',')     # split string using delimiter comma
 
['how', 'to', 'do', 'in', 'java'] #Output

4.用多个定界符分割

字符串对象的 拆分() 方法实际上适用于非常简单的情况,并且不允许使用多个定界符或考虑定界符周围可能存在的空格。

如果您需要更多灵活性,请使用 重新拆分() 方法:

>>> import re
 
>>> line = 'how to; do, in,java,      dot, com'
 
>>> re.split(r'[;,\s]\s*', line) # split with delimiters comma, semicolon and space 
                                             # followed by any amount of extra whitespace.
 
['how', 'to', 'do', 'in', 'java', 'dot', 'com']

When using 重新拆分(), we need to be a bit careful should the regular expression pattern involve a capture group enclosed in parentheses. 如果使用捕获组,则匹配的文本也会包含在结果中。

例如,看看这里发生了什么:

>>> import re
 
>>> line = 'how to; do, in,java,      dot, com'
 
>>> re.split(r'(;|,|\s)\s*', line) # split with delimiters comma, semicolon and space 
                                               # followed by any amount of extra whitespace.
 
['how', ' ', 'to', ';', 'do', ',', 'in', ',', 'java', ',', 'dot', ',', 'com']

快乐学习!!

地址:https://www.cundage.com/article/split-string.html

相关阅读

Learn to use Python 打印() function to 将 Python 程序或 Python 脚本的打印输出重定向到文件. 1. 使用 文件 参数打印到文件 打印()
在 Python 中,string.count() 用于计算给定输入字符串中字符或子字符串的出现次数。 input_string = "how to do in java" substri...
Python example to 将字符串拆分为 列表 的标记 using the delimiters such as space, comma, 正则表达式, or multiple de...
在 Python 中,capitalize() 方法将字符串大写,即大写给定字符串中的第一个字母,并将所有其他字符(如果有)小写。 除了改变大小写(大写/小写),capitalize() 不会修...
Python example to 将字符串拆分为 列表 的标记 using the delimiters such as space, comma, 正则表达式, or multiple de...
Learn to use Python 打印() function to 将 Python 程序或 Python 脚本的打印输出重定向到文件. 1. 使用 文件 参数打印到文件 打印() 函数接...
Python string.endswith() 用于检查特定文本模式的字符串结尾,例如域名后缀等。 1.字符串endswith()方法 检查字符串结尾的一种简单方法是使用 String.end...
Python bin() 方法将给定的 integer 转换为等效的二进制 < href="https://howtodoinjava.com/python-datatypes/pytho...
学习使用 Python httplib2 模块。 超文本传输协议 (HTTP) 是分布式协作超媒体信息系统的应用协议。 HTTP 是万维网数据通信的基础。 Python httplib2 模块提...
阅读、理解和练习这些 Python 示例,以更好地理解 Python 语言。这些简单的 Python 程序将帮助我们理解 Python 的基本编程概念。 此页面上的所有程序都经过测试,应该可以在...