12、字符串的分割和组合

12.1 str.split():字符串分割函数 
通过指定分隔符对字符串进行切片,并返回分割后的字符串列表。 
语法: 
str.split(s, num)[n] 
参数说明: 
s:表示指定的分隔符,不写的话,默认是空格(’ ‘)。如果字符串中没有给定的分隔符时,则把整个字符串作为列表的一个元素返回。 
num:表示分割次数。如果指定了参数num,就会将字符串分割成num+1个子字符串,并且每一个子字符串可以赋给新的变量。 
[n]:表示选取第n个分片,n表示返回的list中元素下标,从0开始的。

12.2 os.path.split():路径文件分割函数 
按照路径将文件名和路劲分割开,这里需要引入os包(import os)。 
语法: 
os.path.split(‘PATH’) 
参数说明: 
PATH指一个文件所在的绝对路劲 
实例: 
1)、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

2)、统计字符串中出现的单词个数

>>> str2 = "This is the voa special english health report"
>>> list1 = str2.split(' ')
>>> list1
['This', 'is', 'the', 'voa', 'special', 'english', 'health', 'report']
>>> len(list1)
8

3)、多次连续使用split()函数 
例如:将从html代码中提取网站地址

>>> s = '<a href="www.test.com">test</a>'
>>> print s.split('"')[1]
www.test.com
>>> print s.split('"')[1].split('.')
['www', 'test', 'com']

4)、使用split()函数去除一些特殊字符

#去掉字符串中的换行符\n
>>> str2 = '''hello
... world
... !'''
>>> str2.split('\n')
['hello', 'world', '!']

5)、分割文件和其路劲

>>> import os
>>> print os.path.split("d:\test\a.txt")
('d:', '\test\x07.txt')
>>> print os.path.split('d:/test/a.txt')
('d:/test', 'a.txt')
>>> print os.path.split('d:\\test\\a.txt')
('d:\\test', 'a.txt')

从上面的结果可以看出,如果我们路劲写成d:\test\a.txt,是得不到我们想要的结果,必须将再加一个’\’来转义第二个’\’才行,或者直接写成d:/test/a.txt这样。

12.3 str.join(seq):将序列组合成字符串函数 
语法:s.join(seq) 
参数说明: 
s:给定的连接符 
seq:代表要连接的序列,如list、tuple、str的序列 
实例: 
1)、普通字符串的连接(只能针对字符或字符串进行连接)

>>> '-'.join("abdcd")
'a-b-d-c-d'
>>> list1 = ['a','b','c']
>>> ''.join(list1)
'abc'

2)、字符串分割函数和字符串组合函数组合使用的情况

>>> s = '<a href="www.test.com">test</a>'
>>> print s.split('"')[1]
www.test.com
>>> print s.split('"')[1].split('.')
['www', 'test', 'com']
>>> print '.'.join(s.split('"')[1].split('.'))
www.test.com

来源于 https://blog.csdn.net/seetheworld518/article/details/47346527

Python字符串操作之字符串分割与组合的更多相关文章

  1. awk字符串操作(字符串链接、传入传出shell变量)

    1.awk基础 awk的环境变量及其意义   https://blog.csdn.net/snowpay/article/details/52451718 linux awk命令详解 https:// ...

  2. 【转载】Python字符串操作之字符串分割与组合

    1. str.split():字符串分割函数 通过指定分隔符对字符串进行切片,并返回分割后的字符串列表. 语法: str.split(s, num)[n] 参数说明: s:表示指定的分隔符,不写的话, ...

  3. python基础操作_字符串操作_列表操作list

    #字符串可以通过下表取值,如下程序 names='java python' print(names[0],names[5]) #使用for循环轮询所有name值 ''' for name in nam ...

  4. 【ORACLE】字符串操作 B字符串时A的一部分

    select * from a where instr(a,b)>0;用于实现B字段是A字段中的某一部分的时候,要论顺序或者要相邻的字符. 如果想要不论顺序或者不相邻的字符时,定义函数可以实现: ...

  5. C#入门篇6-7:字符串操作 看看字符串的特殊之处 值类型与引用类型的区别

    //看看字符串的特殊之处值类型与引用类型的区别 public static void CompareString(string stra, string strb, int i) { #region ...

  6. python基础--字符串操作、列表、元组、文件操作

    一.变量及条件判断 1.字符串.布尔类型.float.int类型,None都是不可变变量 2.字符串是不可变变量,不可变变量就是指定义之后不能修改它的值 3.count +=1和count=count ...

  7. [Python Study Notes]字符串操作

    字符串操作 a.字符串格式化输出 name = "liu" print "i am %s " % name     #输出: i am liu   PS: 字符 ...

  8. Python 字符串操作,截取,长度

    1.字符串操作: 字符串长度: s = "; slen = len(s); 字符串截取: print s[:-:-] #截取,逆序隔1个取一个字符 print s[:-:-] #截取,逆序隔 ...

  9. python预课02 time模块,文本进度条示例,数字类型操作,字符串操作

    time模块 概述:time库是Python中处理时间的标准库,包含以下三类函数 时间获取: time(), ctime(), gmtime() 时间格式化: strftime(), strptime ...

随机推荐

  1. springboot+cloud 学习(三)消息中间件 RibbitMQ+Stream

    安装RabbitMQ window下安装: (1):下载erlang,原因在于RabbitMQ服务端代码是使用并发式语言erlang编写的,下载地址:http://www.erlang.org/dow ...

  2. [转]JS组件系列——Bootstrap组件福利篇:几款好用的组件推荐

    本文转自:https://www.cnblogs.com/landeanfen/p/5461849.html#_label3 阅读目录 一.时间组件 1.效果展示 2.源码说明 3.代码示例 二.自增 ...

  3. C# 性能优化 之 秒表 Stopwatch。

    生词解释:Diagnostics[,daɪəg'nɑstɪks] n.诊断学 using System.Diagnostics; Stopwatch sw = new Stopwatch (); sw ...

  4. T-SQL:基础练习(杂)

    1.返回 每月最后一天订单 SELECT orderid, orderdate, custid, empid FROM Sales.Orders WHERE orderdate = EOMONTH(o ...

  5. idea创建maven项目速度慢?别急,这有三种方案

    困扰 Intellij idea是一款非常强大的编辑器,可以很方便地帮我们创建maven项目,有用过的同学应该都深有体会,但我们经常会遇到一个困扰,那就是用idea创建maven项目时,速度很慢,往往 ...

  6. 详解promise、async和await的执行顺序

    1.题目和答案 一道题题目:下面这段promise.async和await代码,请问控制台打印的顺序? async function async1(){ console.log('async1 sta ...

  7. 百度地图坐标偏移,微信小程序地图偏移问题,腾讯地图坐标偏移

    解决方案: 如果用百度的地图获取的坐标点,在微信小程序内使用,就会出现偏移 算法(lat和lng是经纬度,球面坐标): To_B是转到百度,To_G是转到GCJ-02(谷歌,高德,腾讯) var TO ...

  8. 在JSP中获取oracle中的时间戳类型的字段并显示

    在oracle中有一种特殊的时间显示类型——Timestamp时间戳 通常我们将当前时间转化为时间戳的语法如下: select cast (sysdate as timestamp ) from du ...

  9. Docker 搭建 ELK 收集并展示 tomcat 日志

    架构 前端展示 --> 索引搜索 <-- 日志提取及过滤 --> 日志缓存 <-- 日志收集 Kibana --> Elastash <-- Logstash -- ...

  10. sql server:查詢系統表

    ---查看所有存储过程或视图的位置 select a.name,a.[type],b.[definition] from sys.all_objects a,sys.sql_modules b whe ...