Python總結第三篇之字符串

字符串算是python 文本處理中用到的非常多的內容了,下面就對此總結下。

查找字符串

#!usr/bin/env 
import re
import string

target = 'test.txt'
file = open(target) 
keyword = 'help'

for line in file:
	# 這一行的目的是爲了查看,是否有從首位開始就與keyword匹配的字符串
	if re.match(keyword, line.strip()) == None:
		print line
	else:
		print 'yes'
					
	# 這一行的目的是爲了確認是否包含keyword,並不要求必須從首位開始
	if line.find(keyword) > 0 or line.find(keyword) == 0:
		print line	
# text.txt
123
hello
123hello456

執行結果如下:

loop 1
123
loop 2
yes
hello
loop 3
123hello456
123hello456

查找固定格式字符串

比如需要查找下類似:
0x00 格式的字符串,長度不固定

import re
import string

strname = "hello 0x1234 world"

model = re.comple("0x\w+")
str1 = model.findall(strname)
if len(str1):
	for i in str1:
		value = int(str, 16)
		print value

結果如下:

1234

去除字符串

ss = '\naabb cc,\n dd\n\n\n'
print ss.strip('\n')
print ss.lstrip('\n') #刪除ss字符串開頭處的指定字符,
print ss.rstrip('\n') #刪除ss結尾處的指定字符
print ss.replace('\n', '')
aabb cc,\n dd
aabb cc,\n dd\n\n\n
\naabb cc,\n dd
aabb cc,dd

注意: string.strip()參數爲空時,默認去除ss字符串中頭尾\r, \t, \n, 空格等字符

字符串轉數字

int(str, base)

比如上列中的:
int(str, 16) 轉化成16進制的數字.

工具網站

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章