python的split分割字符串
时间: 2023-11-11 14:57:10 浏览: 80
Python的split()方法是用于将字符串按照指定的分隔符进行分割,并返回分割后的子字符串列表。可以通过以下方式使用split()方法进行字符串的分割:
1. 分割指定个数的字符:
string = "Python is a good language"
content = string.split(" ", 2) # 分隔前2个字符串
print(content) # ['Python', 'is', 'a good language']
2. 分割其他规律的指定分隔符:
string = "Hi:Tom"
content = string.split(":")
print(content) # ['Hi', 'Tom']
key = string.split(":")
print(key) # Hi
value = string.split(":")
print(value) # Tom
string = "abc#def#xyz"
content = string.split("#")
print(content) # ['abc', 'def', 'xyz']
content1 = string.split("#")
print(content1) # abc
content2 = string.split("#")
print(content2) # def
content3 = string.split("#")
print(content3) # xyz
3. 获取某一个切割的字符:
string = "Python is a good language"
content = string.split(" ") # 获取分隔的第四个字符
print(content) # language
阅读全文