python基礎===拆分字串,和拼接字串

來源:互聯網
上載者:User

標籤:font   type   漢字   nts   elements   family   des   特殊符號   copy   

給定某字元,只需要保留其中的有效漢字或者字母,數字之類的。去掉特殊符號或者以某種格式進行拆分的時候,就可以採用re.split的方法。例如

=============================== RESTART: Shell ===============================>>> s = ‘‘‘Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32Type "copyright", "credits" or "license()" for more information.‘‘‘>>> s‘Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32\nType "copyright", "credits" or "license()" for more information.‘>>> #現在要對s拆分,去掉裡面多餘的字元,只提取 數字,字母這些有效字元。>>> >>> import re>>> x = re.split(r‘[.(:,[)" ]‘, s)    #把特殊符號和空格都作為拆分條件輸入[‘Python‘, ‘3‘, ‘6‘, ‘1‘, ‘‘, ‘v3‘, ‘6‘, ‘1‘, ‘69c0db5‘, ‘‘, ‘Mar‘, ‘21‘, ‘2017‘, ‘‘, ‘18‘, ‘41‘, ‘36‘, ‘‘, ‘‘, ‘MSC‘, ‘v‘, ‘1900‘, ‘64‘, ‘bit‘, ‘‘, ‘AMD64‘, ‘]‘, ‘on‘, ‘win32\nType‘, ‘‘, ‘copyright‘, ‘‘, ‘‘, ‘‘, ‘credits‘, ‘‘, ‘or‘, ‘‘, ‘license‘, ‘‘, ‘‘, ‘‘, ‘for‘, ‘more‘, ‘information‘, ‘‘]>>> >>> words = [i for i in x if i]>>> words[‘Python‘, ‘3‘, ‘6‘, ‘1‘, ‘v3‘, ‘6‘, ‘1‘, ‘69c0db5‘, ‘Mar‘, ‘21‘, ‘2017‘, ‘18‘, ‘41‘, ‘36‘, ‘MSC‘, ‘v‘, ‘1900‘, ‘64‘, ‘bit‘, ‘AMD64‘, ‘]‘, ‘on‘, ‘win32\nType‘, ‘copyright‘, ‘credits‘, ‘or‘, ‘license‘, ‘for‘, ‘more‘, ‘information‘]>>> 

 

 

 

 

使用S.join() 方法拼接:

>>> #字串的拼接>>> >>> help(str.join)Help on method_descriptor:join(...)    S.join(iterable) -> str        Return a string which is the concatenation of the strings in the    iterable.  The separator between elements is S.>>> l = list(range(1,9))>>> >>> s = "".join([str(i) for i in l])>>> s‘12345678‘>>> s = "".join(str(i) for i in l)>>> s‘12345678‘>>> 

 

python基礎===拆分字串,和拼接字串

聯繫我們

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