【Python 3.6.1】split()方法
描述:split()方法,通过指定分隔符对字符串进行拆分为list
语法:
1 |
str.split(分隔符,拆分次数) |
分隔符:默认为所有的空字符,当然也可以是逗号、空格、换行(\n)、制表符(\t)等。
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 |
[root@dt xxf]# python3 Python 3.6.1 (default, Jul 2 2017, 16:09:42) [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> # s1为字符串 >>> s1='C,C++,Java,Oracle,Perl,Pythone' >>> print (s1,type(s1)) C,C++,Java,Oracle,Perl,Pythone <class 'str'> >>> # 将s1按照逗号拆分,那么拆分后为list >>> s2=s1.split(',') >>> print (s2,type(s2)) ['C', 'C++', 'Java', 'Oracle', 'Perl', 'Pythone'] <class 'list'> >>> # 当split方法中未指定分隔符,那么默认为空格 >>> s3 = 'Hello World' >>> print (s3,s3.split()) Hello World ['Hello', 'World'] >>> # 指定拆分次数 >>> s4 = 'This is Our Classroom' >>> print (s4.split(" ",2)) ['This', 'is', 'Our Classroom'] >>> |
上面的测试可以清除的看到,一个字符串,按照指定分隔符拆分为一个list,那么这个动作有什么用呢?
工作中我遇到了这样的需求:
在一个配置文件中,一个键值对中的value(就是类似我上面描述的那个字符串)这个字符串拆分后,是另外一个配置文件的section,所以通过split就可以完美的解决这个问题,以下是我需求的大致意思:
配置文件1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
[root@dt xxf]# cat tabname.conf [t1] type = 1 state = 0 [t2] type = 1 state = 0 [t3] type = 1 state = 0 [t4] type = 1 state = 0 [t5] type = 1 state = 0 [root@dt xxf]# |
配置文件2:
1 2 3 4 5 |
[root@dt xxf]# cat init.conf [init] istrue = T tabname = t1,t2,t3 [root@dt xxf]# |
程序功能描述:程序功能是两个数据库的数据同步,正常情况下,所有的表都需要同步,那么当遇到特殊情况,也许只需要同步一张或几张表,通过以下配置,可以很方便的做这方面的控制。
先读init.conf配置文件,判断istrue的value,如果为1则表示只对t1,t2,t3这三张表进行处理,否则,将对tabname.conf中所有的section中指定的表名进行处理。
代码如下:
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 |
[root@dt xxf]# cat split.py import configparser # 初始化实例,得到一个对象cf cf = configparser.ConfigParser() # 读取相对路径下的db.conf文件 cf.read("tabname.conf") # 读配置文件中所有的section,以数组的形式显示 sec = cf.sections() # 读取init.conf配置文件 cf.read("init.conf") # 获取init配置文件中myinit的的所有键值 IsTrue = cf.get("myinit","istrue") TabName = cf.get("myinit","tabname") # 判断键值istrue的value,如果是“T”那么就将tabname字符串拆分,赋予sec if IsTrue == "T": sec = TabName.split(',') # for循环读取list for i in sec: print (i) [root@dt xxf]# |
测试效果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# 当init配置文件中istrue = T时,打印如下表名 [root@dt xxf]# cat init.conf |grep istrue istrue = T [root@dt xxf]# python3 split.py t1 t2 t3 [root@dt xxf]# # 当init配置文件中istrue = F时,打印如下表名 [root@dt xxf]# cat init.conf |grep istrue istrue = F [root@dt xxf]# python3 split.py t1 t2 t3 t4 t5 [root@dt xxf]# |
之所以这么做,是因为软件设计的问题,也许你有更好的办法实现类似的功能。