python分割和拼接字串

來源:互聯網
上載者:User
關於string的split 和 join 方法
對匯入os模組進行os.path.splie()/os.path.join() 貌似是處理機制不一樣,但是功能上一樣。

1.string.split(str=' ',num=string.count(str)):  以str為分隔,符切片string,如果num有指定值,則僅分隔num個子字串。
S.split([sep [,maxsplit]]) -> 由字串分割成的列表 返回一組使用分隔字元(sep)分割字串形成的列表。如果指定最大分割數,則在最大分割時結束。
如果分隔字元未指定或者為none,則分隔字元預設為空白格。
注意:分隔字元不可為空,否則會出錯,但是可以有不含其中的分隔字元。
os.path.split()
os.path.split是按照路徑將檔案名稱和路徑分割開,比如d:\\python\\python.ext,可分割為['d:\\python', 'python.exe']

代碼如下:


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.string.join(sep):  以string作為分割符,將sep中所有的元素(字串表示)合并成一個新的字串。
將join裡字串、元祖、列表的所有元素通過分隔字元串連成一個新的字串(字串、元祖、列表它們是序列類型,有著相同的訪問方式)
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'


例子:
寫一個函數,參數為一個長字串和一個word,將長字串中是word的改為對應字母個數的**,比如,長字串為“this hack is wack hack”,word為“hack”,那麼要求函數輸出:“this **** is wack ****”

代碼如下:


def censor(text,word):
texts = text.split(" ")
for i in range(len(texts)):if texts[i] == word:
texts[i] = "*" * len(word)
return " ".join(texts)
print censor("hey hey hey","hey")


輸出:
*** *** ***
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.