Python struct.unpack
更新時間:2008年09月06日 14:07:52 作者:
Python中按一定的格式取出某字符串中的子字符串,使用struck.unpack是非常高效的。
1. 設置fomat格式,如下:
# 取前5個字符,跳過4個字符華,再取3個字符
format = '5s 4x 3s'
2. 使用struck.unpack獲取子字符串
import struct
print struct.unpack(format, 'Test astring')
#('Test', 'ing')
來個簡單的例子吧,有一個字符串'He is not very happy',處理一下,把中間的not去掉,然后再輸出。
import struct
theString = 'He is not very happy'
format = '2s 1x 2s 5x 4s 1x 5s'
print ' '.join(struct.unpack(format, theString))
輸出結果:
He is very happy
復制代碼 代碼如下:
# 取前5個字符,跳過4個字符華,再取3個字符
format = '5s 4x 3s'
2. 使用struck.unpack獲取子字符串
復制代碼 代碼如下:
import struct
print struct.unpack(format, 'Test astring')
#('Test', 'ing')
來個簡單的例子吧,有一個字符串'He is not very happy',處理一下,把中間的not去掉,然后再輸出。
復制代碼 代碼如下:
import struct
theString = 'He is not very happy'
format = '2s 1x 2s 5x 4s 1x 5s'
print ' '.join(struct.unpack(format, theString))
輸出結果:
He is very happy
相關文章
Python使用psycopg2連接PostgreSQL數據庫的步驟
PostgreSQL 是一個廣泛使用的開源對象關系數據庫系統,以其強大的功能和靈活性而聞名,Python,作為一種流行的編程語言,提供了多種方式與數據庫交互,其中 psycopg2 是連接 PostgreSQL 數據庫的流行選擇之一,本文介紹了Python使用psycopg2連接PostgreSQL數據庫的步驟2024-12-12
Tensorflow: 從checkpoint文件中讀取tensor方式
今天小編就為大家分享一篇Tensorflow: 從checkpoint文件中讀取tensor方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

