Python3 split()方法

描述
split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串

语法
split()方法语法:

str.split(str="", num=string.count(str))
参数
str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num – 分割次数。
返回值
返回分割后的字符串列表。

实例
以下实例展示了split()函数的使用方法:

#!/usr/bin/python3

str = "this is string example....wow!!!"
print (str.split( ))
print (str.split('i',1))
print (str.split('w'))
以上实例输出结果如下:

['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
Python3 字符串

注:split()分割字符串返回的是列表

利用re模块分割含有多种分割符的字符串:

import re
a='Beautiful, is; better*than\nugly'
# 四个分隔符为:, ; * \n
x= re.split(',|; |\*|\n',a)
print(x)
1
2
3
4
5
6
应用

网页地址解析

#coding=utf-8

str="http://www.runoob.com/python/att-string-split.html"
print("0:%s"%str.split("/")[-1])
print("1:%s"%str.split("/")[-2])
print("2:%s"%str.split("/")[-3])
print("3:%s"%str.split("/")[-4])
print("4:%s"%str.split("/")[-5])

print("5:%s"%str.split("/",-1))
print("6:%s"%str.split("/",0))
print("7:%s"%str.split("/",1))
print("8:%s"%str.split("/",2))
print("9:%s"%str.split("/",3))
print("10:%s"%str.split("/",4))
print("11:%s"%str.split("/",5))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
结果为

0:att-string-split.html
1:python
2:www.runoob.com
3:
4:http:
5:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']
6:['http://www.runoob.com/python/att-string-split.html']
7:['http:', '/www.runoob.com/python/att-string-split.html']
8:['http:', '', 'www.runoob.com/python/att-string-split.html']
9:['http:', '', 'www.runoob.com', 'python/att-string-split.html']
10:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']
11:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']
1
2
3
4
5
6
7
8
9
10
11
12
处理表格文件
date.txt文件如下
1 0.0888 201 36.02 28 0.5885
2 0.1399 198 39.32 30 0.8291
…

import os
data = []
for lines in open(r"date.dat",'r').readlines():
lines.strip()
s = [x for x in lines.strip().split()]
data.append(s)

print(data)
print(len(data[0]))
1
2
3
4
5
6
7
8
9
Python splitlines()方法
Python splitlines() 按照行(‘\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符

str.splitlines([keepends])
keepends – 在输出结果里是否去掉换行符(‘\r’, ‘\r\n’, \n’),默认为 False,不包含换行符,如果为 True,则保留换行符。

str1 = 'ab c\n\nde fg\rkl\r\n'
print str1.splitlines();

str2 = 'ab c\n\nde fg\rkl\r\n'
print str2.splitlines(True)

#返回结果
['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
1
2
3
4
5
6
7
8
9
join()方法
Python中有join()和os.path.join()两个函数,具体作用如下:
join(): 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
os.path.join(): 将多个路径组合后返回

join()方法将列表中的字符元素合并为一个大的字符串

一、函数说明
1、join()函数
语法: ‘sep’.join(seq)
参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串

返回值:返回一个以分隔符sep连接各个元素后生成的字符串

2、os.path.join()函数

语法: os.path.join(path1[,path2[,……]])
返回值:将多个路径组合后返回
注:第一个绝对路径之前的参数将被忽略

#对序列进行操作(分别使用' '与':'作为分隔符)

>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido

#对字符串进行操作

>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o

#对元组进行操作

>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido

#对字典进行操作

>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello

#合并目录

>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
strip()方法
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。
str.strip([chars])
参数 chars – 移除字符串头尾指定的字符。

str = "0000000this is string example....wow!!!0000000"
print (str.strip( '0' ))
1
2
输出:

this is string example....wow!!!
1
replace()
描述
Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

语法
replace()方法语法:

str.replace(old, new[, max])

参数

old – 将被替换的子字符串。
new – 新字符串,用于替换old子字符串
max – 可选字符串, 替换不超过 max 次

返回值
返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

实例

#!/usr/bin/python
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
1
2
3
4
5
输出:

thwas was string example….wow!!! thwas was really string
thwas was string example….wow!!! thwas is really string
---------------------
原文:https://blog.csdn.net/qq_40170358/article/details/79774154

python中字符串拆分与合并——split()、join()、strip()和replace()的更多相关文章

  1. Python中字符串操作函数string.split('str1')和string.join(ls)

    Python中的字符串操作函数split 和 join能够实现字符串和列表之间的简单转换, 使用 .split()可以将字符串中特定部分以多个字符的形式,存储成列表 def split(self, * ...

  2. 【Python从入门到精通】(九)Python中字符串的各种骚操作你已经烂熟于心了么?

    您好,我是码农飞哥,感谢您阅读本文,欢迎一键三连哦. 本文将重点介绍Python字符串的各种常用方法,字符串是实际开发中经常用到的,所有熟练的掌握它的各种用法显得尤为重要. 干货满满,建议收藏,欢迎大 ...

  3. python中字符串的操作方法

    python中字符串的操作方法大全 更新时间:2018年06月03日 10:08:51 作者:骏马金龙 我要评论这篇文章主要给大家介绍了关于python中字符串操作方法的相关资料,文中通过示例代码详细 ...

  4. 超详细!盘点Python中字符串的常用操作

    在Python中字符串的表达方式有四种 一对单引号 一对双引号 一对三个单引号 一对三个双引号 a = 'abc' b= "abc" c = '''abc''' d = " ...

  5. Python中字符串有哪些常用操作?纯干货超详细

  6. Python中字符串String的基本内置函数与过滤字符模块函数的基本用法

    Python中字符串String的基本内置函数与用法 首先我们要明白在python中当字符编码为:UTF-8时,中文在字符串中的占位为3个字节,其余字符为一个字节 下面就直接介绍几种python中字符 ...

  7. python中字符串的几种表达方式(用什么方式表示字符串)

    说明: 今天在学习python的基础的内容,学习在python中如何操作字符串,在此记录下. 主要是python中字符串的几种表达,表示方式. python的几种表达方式 1 使用单引号扩起来字符串 ...

  8. 基于Python中numpy数组的合并实例讲解

    基于Python中numpy数组的合并实例讲解 下面小编就为大家分享一篇基于Python中numpy数组的合并实例讲解,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 Python中n ...

  9. Python中字符串与字节之间相互转换

    Python中字符串与字节之间相互转换 ​ a = b"Hello, world!" # bytes object b = "Hello, world!" # ...

随机推荐

  1. Java 包装类笔记

    @(JDK)[包装类] Java 包装类笔记 当需要使用到集合的时候,如果是基础数据类型,需要转换为包装类,再使用,在JDK1.5之前,每次使用的时候,都需要手动转换为包装类(称为装箱),然后在使用的 ...

  2. win10更新失败——适用于Windows 10 Version 1709 的03累积更新,适合基于x64系统(KB4088776)更新失败

    相信最近很多人被windows的更新折磨坏了,下面来介绍一下解决办法,有用的话请点赞! 首先将C盘中的这个文件夹删除:"C:\Windows\System32\Tasks\Microsoft ...

  3. 如何优雅的关闭Java线程池

    面试中经常会问到,创建一个线程池需要哪些参数啊,线程池的工作原理啊,却很少会问到线程池如何安全关闭的. 也正是因为大家不是很关注这块,即便是工作三四年的人,也会有因为线程池关闭不合理,导致应用无法正常 ...

  4. php中的session_id详解

    php中session_id()函数原型及说明session_id()函数说明:stringsession_id([string$id])session_id() 可以用来获取/设置 当前会话 ID. ...

  5. Python人脸识别最佳教材典范,40行代码搭建人脸识别系统!

    Face Id是一款高端的人脸解锁软件,官方称:"在一百万张脸中识别出你的脸."百度.谷歌.腾讯等各大企业都花费数亿来鞭策人工智能的崛起,而实际的人脸识别技术是否有那么神奇? 绿帽 ...

  6. 魔咒,90%未学满三个月Python编程的朋友都会出错!

    Python语言虽然优美,简洁和强大,但是也有很多坑,一不小心就会掉进去.我学Python的时候也遇到过,今天总结一下,希望对大家能有收获! Python的默认参数就被创建 一次,而不是每次调用函数的 ...

  7. ArcCore重构-Platform_Types.h实现辨析

    AUTOSAR定义了一系列PlatformTypes,如uint8/uint16/uint32等等基本类型. It contains all platform dependent types and ...

  8. 夜神模拟器链接Android studoid

    在cmd 窗口输入:adb.exe connect 127.0.0.1:62001然后as就自动匹配了夜神经常忘记,特此提醒

  9. mysql事务之间的隔离级别

    事务间未做隔离,会引起下面这些问题. 1.脏读:一个事务可读到另外一个尚未commit的事务中的数据. 2.不可重复读:在一个事务中,读取同一个数据 a,b,按顺序读取,在读a  b 之间,另外一个事 ...

  10. Java bean和json互转时,屏蔽某个属性

    有的时候我们把java bean 转换成json的时候,希望屏蔽掉某个属性,这时可以在java bean的属性上加上@JsonIgnore注解,在com.fasterxml.jackson.annot ...