7招秘籍 教你玩轉Python字串

2021-08-16 11:47:15 字數 2843 閱讀 6992

日常使用python經常要對文字進行處理,無論是爬蟲的資料解析,還是大資料的文字清洗,還是普通檔案的處理,都是要用到字串. python對字串的處理內建了很多高效的函式,非常方便功能很強大.下面是我總結的常用的7招,有了這幾招就能輕鬆應對字串處理.

連線和合併

相加 //兩個字串可以很方便的通過』+』連線起來

str1="hello"

str2="world"

new_str=str1+str2

print

(new_str)

>>helloworld

合併//用join方法

url=['www','python','org']

print (''.join(url))

>>www.python.org

1).相乘//比如寫**的時候要分隔符,用python很容易實現

line='*'*30

print (line)

>>*****

*****

*****

*****

*****

*****

2).切片

str='monday is a busy day'

print (str[0:7])//表示取第乙個到第7個字元

>>monday

print (str[-3:])

>>day 表示取倒數第三個字元開始到結尾

print (str[::])

>>monday is a busy day

普通的分割,用split

split只能做非常簡單的分割,而且不支援多個分隔

phone='400-800-800-1234'

print(phone.split('-'))

>>['400', '800', '800', '1234']

複雜的分割

r表示不轉義,分隔符可以是;或者,或者空格後面跟0個多個額外的空格,然後按照這個模式去分割

import re 

line='hello world; python, i ,like,'

print (re.split(r'[;,s]\s*',line))

>>['hello world', 'python', 'i ', 'like', '']

比方我們要查乙個檔案的名字是以什麼開頭或者什麼結尾

filename='trace.h'

print(filename.endswith('h'))

>>true

print(filename.startswith('trace'))

>>true

一般查詢

我們可以很方便的在長的字串裡面查詢子字串,會返回子字串所在位置的索引, 若找不到返回-1

title='python can be easy to pick up and powerfullanguages'

print ('title.find('pick up'))

>>22

複雜的匹配

mydata='11/27/2016'

if re.match(r'\d+\d+\d+',mydata):

print ('ok,match')

else:

print ('ko,not match')

>>ok,match

6.字串的替換

普通的替換//用replace就可以

title='python can be easy to learn ,powerful languages'

print (title.replace('learn','study'))

>>python can be easy to study ,powerful languages

複雜的替換//若要處理複雜的或者多個的替換,需要用到re模組的sub函式

students='boy 103,gril 105'

print (re.sub(r'\d+',100,students))

>>'boy 100,girl 100'

7.字串中去掉一些字元

去除空格//對文字處理的時候比如從檔案中讀取一行,然後需要去除每一行的兩側的空格,table或者是換行符

line='  congratulations, you guessed it.     '

print(line.strip())

>>congratulations, you guessed it.

注意:字串內部的空格不能去掉,若要去掉需要用re模組
複雜的文字清理,可以利用str.translate,

先構建乙個轉換表,table是乙個翻譯表,表示把』t」o』轉成大寫的』t』 『o』,

instr='to'

outstr='to'

table=str.maketrans(instr,outstr)

old_str='hello world ,welcome to

use python'

new_str=old_str.translate(table)

print (new_str)

>>hello world ,welcome to

use python

91xcz 教你玩轉windows7快捷鍵

微軟公司新推出的windows 7系統有許多令人意想不到的新功能,這些功能值得我們慢慢去了解和發掘,今天一起玩轉windows7的快捷鍵。1 windows鍵 向上方向鍵 可以使當前使用的視窗最大化。windows鍵 向下方向鍵 可以使當前使用中的最大化視窗恢復正常顯示,或者如果當前視窗不是最大化狀...

教你兩招快速解除安裝Python的模組

你是不是自己安裝一大堆python包,然後比如想換個conda來玩,一頓 pip list發現好多!乙個乙個解除安裝那不是要解除安裝到明年?教你乙個好方法 首先,隨便開啟乙個目錄下的cmd,執行 txt檔名自己取 pip freeze python modules.txt這時候你會發現所有的pyth...

python 基礎7 字典

主要方法 keys values items get update 基本結構 info 字典的value可以是任意值 布林值 列表 字典不能作為字典的key 字典無序 info k4 q w 55,66 true ww print info 通過索引查詢到指定元素 v info k3 print v...