python 字符串split
时间: 2023-08-27 13:06:45 浏览: 109
在Python中,字符串的split()方法用于将字符串按照指定的分隔符进行分割,并返回一个包含分割后的子字符串的列表。下面是一些关于字符串split()方法的用法示例:
1. 分隔指定的几个字符:
```python
string = "Python is a good language"
content = string.split(" ", 2) # 分隔前2个字符串
print(content)
```
输出结果为:['Python', 'is', 'a good language']
2. 获取某一个切割的字符:
```python
string = "Python is a good language"
content = string.split(" ")[3] # 获取分隔的第四个字符
print(content)
```
输出结果为:'language'
3. 其他规律的指定的分隔符:
```python
string = "Hi:Tom"
content = string.split(":")
print(content)
key = string.split(":")[0]
print(key)
value = string.split(":")[1]
print(value)
string = "abc#def#xyz"
content = string.split("#")
print(content)
content1 = string.split("#")[0]
print(content1)
content2 = string.split("#")[1]
print(content2)
content3 = string.split("#")[2]
print(content3)
```
输出结果为:
```
['Hi', 'Tom']
Hi
Tom
['abc', 'def', 'xyz']
abc
def
xyz
```
希望以上解答能够帮到你!
阅读全文