python 的split 與join

一. 關於split 和 join 方法:

  1. 只針對字符串進行處理。split:拆分字符串、join鏈接字符python

  2. string.join(sep):以string做爲分割符,將sep中全部的元素(字符串表示)合併成一個新的字符串shell

  3. string.split(str=' ',num=string.count(str)):  以str爲分隔,符切片string,若是num有指定值,則僅分隔num個子字符串。windows

  4. 對導入os模塊進行os.path.splie()/os.path.join() 貌似是處理機制不同,可是功能上同樣。spa

2、split()方法

簡介:
code

split(…)
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator.

實例:ci

s='a b c'
print s.split(' ')
st='hello world'
print st.split('o')
print st.split('o',1)

--------output---------
['a', 'b', 'c']
['hell', ' w', 'rld']
['hell', ' world']

使用注意:字符串

#注意:分隔符不能爲空,不然會出錯以下:
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    s.split('')ValueError: empty separator
    
#可是能夠有不含其中的分隔符
>>> s.split('x')
['a b c']
>>> s.split('xsdfadsf')
['a b c']

os.path.split()
os.path.split是按照路徑將文件名和路徑分割開,好比d:\\python\\python.ext,可分割爲['d:\\python', 'python.exe'],示例以下:string

import os
print os.path.split('c:\\Program File\\123.doc')
print os.path.split('c:\\Program File\\')
-----------------output---------------------
('c:\\Program File', '123.doc')
('c:\\Program File', '')

2、join()

#輸入實例
a='abcd'
print '.'.join(a)   
print '|'.join(['a','b','c'])  #能夠把['a','b','c']看作是 a='abcd';下面同理
print '.'.join({'a':1,'b':2,'c':3,'d':4})

#輸出
a.b.c.d3 
a|b|c4 
a.c.b.d

os.path.join(path1[,path2[,......]])it

os.path.join(path1[, path2[, ...]])

將多個路徑組合後返回,第一個絕對路徑以前的參數將被忽略。

>>> os.path.join('c:\\', 'csv', 'test.csv')

'c:\\csv\\test.csv'

>>> os.path.join('windows\temp', 'c:\\', 'csv', 'test.csv')

'c:\\csv\\test.csv'

>>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c')

'/home/aa/bb/c'
相關文章
相關標籤/搜索