split && join && append

來源:互聯網
上載者:User

標籤:style   使用   os   檔案   amp   size   window   app   

這三個方法個人感覺還是很實用的,並且挺相似的,故放到一起:

 

split && join      
  split 注1 注2
  作用:分割字串;返回一個列表 1.可以分割字串中不存在的字元,返回完整列表:
string = ‘sadhjfhdj‘
print string.split("5")
>>>[‘sadhjfhdj‘]
但是不能將分割符置空!
    2.可以和列表的各類方法結合使用,如切片  
    3.可以添加參數,以確定分割多少個出來:
string = ‘121212121‘
print string.split("2",1)
>>>[‘1‘,‘1212121‘]
 
       
  os.path.split() ex:
import os
print os.path.split("c://Documents and xxx/junzhou/what/file.txt")
>>>(‘c://Documents and xxx/junzhou/what‘, ‘file.txt‘)
 
  作用:將路徑與檔案名稱分割開;返回一個元組    
       
  join ex:
a = (‘a‘,‘b‘,‘c‘,‘d‘)
print ‘‘.join(a)
>>>abcd
b = [‘1‘,‘2‘,‘3‘,‘4‘]
print ‘‘.join(b)
>>>123456
c = ‘123456‘
print ‘.‘.join©
>>>1.2.3.4.5.6
 
  os.path.join() ex:
print os.path.join(‘windows\temp‘, ‘c:\\‘, ‘csv‘, ‘test.csv‘)
>>>c:\csv\test.csv
print os.path.join(‘c:\\‘, ‘csv‘, ‘test.csv‘)
>>>c:\csv\test.csv
第一個絕對路徑之前的參數將會被忽略!

append:

append是list的方法,即將元素添加到list尾部:

a = [‘1‘,‘2‘,‘3‘]
a.append(4)
print a

>>>[‘1‘,‘2‘,‘3‘,‘4‘]

 

這裡有一點需要和join做一下說明:append是針對list的,因此不管什麼list 都能實現,而join只針對str類型,若是當需要對一個list進行串連時,這個list中的每一項必須是str類型

如:

a = [1,2,3,4]

print ‘.‘.join(a)

>>>報錯異常,因為list a中的項為int型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.