【轉載】Python字符串操做之字符串分割與組合

一、 str.split():字符串分割函數
  經過指定分隔符對字符串進行切片,並返回分割後的字符串列表。
  語法:
  str.split(s, num)[n]
  參數說明:
  s:表示指定的分隔符,不寫的話,默認是空格(’ ‘)。若是字符串中沒有給定的分隔符時,則把整個字符串做爲列表的一個元素返回。
  num:表示分割次數。若是指定了參數num,就會將字符串分割成num+1個子字符串,而且每個子字符串能夠賦給新的變量。
  [n]:表示選取第n個分片,n表示返回的list中元素下標,從0開始的。html

二、 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)統計字符串中出現的單詞個數spa

>>> 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代碼中提取網站地址.net

>>> 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()函數去除一些特殊字符code

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

   5)、分割文件和其路勁htm

>>> 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這樣。blog

 

三、 str.join(seq):將序列組合成字符串函數 
  語法:s.join(seq) 
  參數說明: 
  s:給定的鏈接符 
  seq:表明要鏈接的序列,如list、tuple、str的序列 
實例: ci

  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

相關文章
相關標籤/搜索