[Python Study Notes]字串處理技巧(持續更新)

來源:互聯網
上載者:User

標籤:ring   quick   str   bar   star   .com   comm   檔案   dict   

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘>>檔案: 字串處理.py>>作者: liu yang>>郵箱: [email protected]>>部落格: www.cnblogs.com/liu66blog‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘#!/usr/bin/env python# -*- coding: utf-8 -*-import sys, os# 1.字串的串連和合并# 相加 //兩個字串可以很方便的通過‘+‘串連起來str1=‘123‘str2=‘456‘str3=str1+str2print(str3)# -----------輸出----------------------# 123456# ------------------------------------# 合并//用join方法url=[‘www‘,‘cnblog‘,‘com/liu66blog‘]print(‘.‘.join(url))# -----------輸出----------------------# www.cnblog.com/liu66blog# ------------------------------------# 2.字串的切片和相乘# 相乘//比如寫代碼的時候要分隔字元,用python很容易實現Separator=‘*‘*30print(Separator)# -----------輸出----------------------# ******************************# ------------------------------------# 切片操作url=‘www.cnblogs.com/liu66blog‘# 取下標0-15個字元print(url[0:16])# 取下標16-最後一個print(url[16:])# 取倒數第四個到最後print(url[-4:])# 複製字串print(url[::])# -----------輸出----------------------# www.cnblogs.com/# liu66blog# blog# www.cnblogs.com/liu66blog# ------------------------------------# 3.字串的分割# 普通的分割,用split# split只能做非常簡單的分割,而且不支援多個分隔url=‘www.cnblogs.com/liu66blog‘url_list=url.split(‘.‘)print(url_list)# -----------輸出----------------------# [‘www‘, ‘cnblogs‘, ‘com/liu66blog‘]# ------------------------------------# 複雜的分割# r表示不轉義,分隔字元可以是;或者,或者/,或者空格後面跟0個多個額外的空格,然後按照這個模式去分割url=‘www.cnblogs.com/liu66blog‘import reurl_list=re.split(r‘[.;/]\s*‘,url)print(url_list)# -----------輸出----------------------# [‘www‘, ‘cnblogs‘, ‘com‘, ‘liu66blog‘]# ------------------------------------# 4.字串的開頭和結尾的處理#  比方我們要查一個名字是以什麼開頭或者什麼結尾url=‘www.cnblogs.com/liu66blog‘result=url.endswith(‘blog‘)print(result)result=url.startswith(‘ww.‘)print(result)# -----------輸出----------------------# True# False# ------------------------------------# 5.字串的尋找和匹配# 一般尋找# 我們可以很方便的在長的字串裡面尋找子字串,會返回子字串所在位置的索引, 若找不到返回-1url=‘www.cnblogs.com/liu66blog‘result=url.find(‘liu66‘)print(result)result=url.find(‘liuyang‘)print(result)# -----------輸出----------------------# 16# -1# ------------------------------------# 複雜尋找data_str=‘2018/2/22‘result=re.match(r‘\d+/\d+/\d+‘,data_str)if result:    print(‘ok,存在‘)# -----------輸出----------------------# ok,存在# ------------------------------------# 6.字串的替換# 普通的替換//用replace就可以url=‘www.cnblogs.com/liu66blog‘url_new=url.replace(‘www.‘,‘‘)print(url_new)# -----------輸出----------------------# cnblogs.com/liu66blog# ------------------------------------# 複雜的替換 利用re.sub函數url=‘www.cnblogs.com/liu66blog‘url_new=re.sub(r‘\d\d‘,‘00‘,url)print(url_new)# -----------輸出----------------------# cnblogs.com/liu00blog# ------------------------------------# 7.字串中去掉一些字元# 去除空格//對文本處理的時候比如從檔案中讀取一行,然後需要去除每一行的兩側的空格,table或者是分行符號url=‘  www.cnblogs.com/liu66blog  ‘url_new=url.strip()print(url_new)# 複雜的文本清理,可以利用str.translate,# 先構建一個轉換表,table是一個翻譯表,表示把‘w‘轉成大寫的‘W‘,# 然後在old_str裡面去掉‘liu66‘,然後剩下的字串再經過table 翻譯# Python3.4已經沒有string.maketrans()了,取而代之的是內建函數:# bytearray.maketrans()、bytes.maketrans()、str.maketrans()url=‘www.cnblogs.com/liu66blog‘# 建立翻譯表instr=‘w‘outstr=‘W‘table=str.maketrans(instr,outstr)url_new=url.translate(table)print(url_new)# -----------輸出----------------------# WWW.cnblogs.com/liu66blog# ------------------------------------# 8.找最長的單詞txt=‘Python is a programming language that lets you work more quickly and integrate your systems more effectively. ‘     ‘You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs. ‘     ‘Learn more about Python..‘# 使用空格分隔txt_list=txt.split(‘ ‘)# 使用sorted()函數按照單詞長度排序txt_list_new=sorted(txt_list,key=lambda x:len(x),reverse=True)# 定義一個空列表,儲存最長的longest_word=[]# 判斷後面的單詞長度for i,word in enumerate(txt_list_new):    if len(txt_list_new[i])<len(txt_list_new[0]):        break    else:        longest_word.append(txt_list_new[i])print(longest_word)# -----------輸出----------------------# [‘effectively.‘, ‘productivity‘]# ------------------------------------# 9.找出指定長度的單詞len_4_word=filter(lambda x:5>len(x)>=4,txt_list)# 注意python3 filter返回不再是列表 需要自己轉換!!len_4_word_list=list(len_4_word)# 轉換成去重元祖len_4_word_tuple=tuple(set(len_4_word_list))print(len_4_word_list)print(len_4_word_tuple)# -----------輸出----------------------# [‘that‘, ‘lets‘, ‘work‘, ‘more‘, ‘your‘, ‘more‘, ‘more‘]# (‘your‘, ‘more‘, ‘lets‘, ‘that‘, ‘work‘)# ------------------------------------# 10.使用最頻繁的單詞from collections import Counter# most_common(x) x代表列舉的個數print(Counter(txt_list).most_common(6))# -----------輸出----------------------# [(‘more‘, 3), (‘and‘, 3), (‘Python‘, 2), (‘is‘, 1), (‘a‘, 1), (‘programming‘, 1)]# ------------------------------------# 11.列出所有大寫的單詞title_words_list=[]for i in txt_list:    if i.istitle():        title_words_list.append(i)# 得到去重字典title_words_dict=set(title_words_list)print(title_words_list)print(title_words_dict)# -----------輸出----------------------# [‘Python‘, ‘You‘, ‘Python‘, ‘Learn‘, ‘Python..‘]# {‘Python..‘, ‘Learn‘, ‘Python‘, ‘You‘}# ------------------------------------# 12.未完待續...

[Python Study Notes]字串處理技巧(持續更新)

聯繫我們

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