python如何切割字符串,,python字符串的
python如何切割字符串,,python字符串的
python字符串的分割方法如下
str.split():字符串分割函数
通过指定分隔符对字符串进行切片,并返回分割后的字符串列表。
语法:
str.split(s, num)[n]
参数说明:
s:表示指定的分隔符,不写的话,默认是空格(’ ‘)。如果字符串中没有给定的分隔符时,则把整个字符串作为列表的一个元素返回。
num:表示分割次数。如果指定了参数num,就会将字符串分割成num+1个子字符串,并且每一个子字符串可以赋给新的变量。
[n]:表示选取第n个分片,n表示返回的list中元素下标,从0开始的。
1.2 os.path.split():路径文件分割函数
按照路径将文件名和路劲分割开,这里需要引入os包(import os)。
语法:
os.path.split(‘PATH’)
参数说明:
PATH指一个文件所在的绝对路径
实例
split()函数常用的一些实例
#定义一个字符串str1>>> str1 = "3w.gorly.test.com.cn"#使用默认分隔符分割字符串str1>>> print str1.split()[‘3w.gorly.test.com.cn‘]#指定分隔符为‘.‘,进行分割字符串str1>>> print str1.split(‘.‘)[‘3w‘, ‘gorly‘, ‘test‘, ‘com‘, ‘cn‘]#指定分隔符为‘.‘,并且指定切割次数为0次>>> print str1.split(‘.‘,0)[‘3w.gorly.test.com.cn‘]#指定分隔符为‘.‘,并且指定切割次数为1次>>> print str1.split(‘.‘,1)[‘3w‘, ‘gorly.test.com.cn‘]#指定分隔符为‘.‘,并且指定切割次数为2次>>> print str1.split(‘.‘,2)[‘3w‘, ‘gorly‘, ‘test.com.cn‘]#这种分割等价于不指定分割次数str1.split(‘.‘)情况>>> print str1.split(‘.‘,-1)[‘3w‘, ‘gorly‘, ‘test‘, ‘com‘, ‘cn‘]#指定分隔符为‘.‘,并取序列下标为0的项>>> print str1.split(‘.‘)[0]3w#指定分隔符为‘.‘,并取序列下标为4的项>>> print str1.split(‘.‘)[4]cn
本文转载于https://www.py.cn/faq/python/12433.html
python如何切割字符串
相关内容
- Python处理PDF和Word文档常用的方法,, Python
- selenium+Python学习之一,,刚入门seleniu
- python3 字典,,字典是另一种可变容器
- ubuntu16 下安装python3.6 和Anaconda3,,1.Python3.
- 代写编程、代写机器学习模型、代写AI python,,代写编程
- 数据分析 - Matplotlib,,简介Matplotl
- 解决:main.py: error: unrecognized arguments: --html,,怎么运行
- Django 框架,,01 web 应用0
- Pytorch-Visdom可视化工具,,Visdom相比Te
- Python2和Python3中的rang()不同之点,, 知道在python
评论关闭