Python中split()函数的用法和示例
split()函数是Python中常用的字符串操作函数,其作用是将字符串按照指定的分隔符进行分割,并返回一个分割后的列表。
该函数用法如下:
str.split(str="", num=string.count(str))
其中,str表示分隔符,默认为空格;num表示分割次数,默认为-1,即分隔符出现次数全都分割。
以下是split()函数用法的示例:
1.使用空格作为分隔符
s = "hello world"
print(s.split()) # ['hello', 'world']
2.使用逗号作为分隔符
s = "one,two,three"
print(s.split(",")) # ['one', 'two', 'three']
3.分割次数为1
s = "one,two,three"
print(s.split(",", 1)) # ['one', 'two,three']
4.使用多个字符作为分隔符
s = "one,two;three,four"
print(s.split(",;")) # ['one', 'two', 'three', 'four']
5.分割空字符串
s = "hello, world,"
print(s.split(",")) # ['hello', ' world', '']
6.分割数字
s = "10,20,30"
print(s.split(",")) # ['10', '20', '30']
7.分割链接
url = "https://www.google.com/search?q=python"
print(url.split("/")) # ['https:', '', 'www.google.com', 'search?q=python']
8.分割换行符
s = "line1
line2
line3"
print(s.split("
")) # ['line1', 'line2', 'line3']
总结:
以上是Python中split()函数的基本用法和示例,使用split()函数可以方便地处理字符串,根据实际需要进行分割或者提取其中的部分内容。
