maketrans和translate函数是进行字符串字符编码的常用方法。本文着重点在于演示其基本用法和在不同版本下操作的差异。本文提到的2.X版本指2.6以上的版本,3.X版本指3.1以上的版本。
2.X版本把字符串基本分为两种:unicode字符串和8位字符串str,后者包含字节数据和我们常见的ASCII码数据;而3.X版本则重新对字符串进行了划分,分为了字节字符串bytes和文本字符串str,两者都是不可变的,所以添加了一个可变的字节字符串类型bytearray。
2.X版本中string类型和str、unicode类型大量方法是重复的,所以3.X版本不提倡使用string模块中与str重复的方法。string模块中还有很多有用的常量和方法,比如string.digits,可以在字符串编码中方便地使用。
2.X中maketrans和translate函数的签名:
string.maketrans(from, to) string.translate(s, table[, deletechars]) str.translate(table[, deletechars]) unicode.translate(table)
3.X中maketrans和translate函数的签名:
static str.maketrans(x[, y[, z]]) static bytes.maketrans(from, to) static bytearray.maketrans(from, to) str.translate(map) bytes.translate(table[, delete]) bytearray.translate(table[, delete])
从中可以看出,相对于2.X的string模块的maketrans方法,3.X中分别提供了三个静态方法用于创建映射表。
下面让我们看一个简单的例子来说明字符串转换的过程:
2.X下的演示过程:
>>> import string #导入string模块 >>> map = string.maketrans('123', 'abc') #建立映射表,将字符串中含有的'1','2','3'替换为'a','b','c' >>> s = '54321123789' #转换前的字符串 >>> s.translate(map) #用创建的映射表map转换字符串 '54cbaabc789' #转换后的字符串
3.X下的演示过程:
>>> map = str.maketrans('123','abc') >>> s = '54321123789' >>> s.translate(map) '54cbaabc789'
2.X使用了string的maketrans函数,而3.X使用了str的maketrans函数,除了这一点,使用方法是基本相同的。若指定字符串中要删除的字符时,使用就会略有不同,如下:
2.X下的演示过程:
>>> import string >>> map = string.maketrans('123', 'abc') >>> s = '54321123789' >>> s.translate(map, '78') #除了转换,还要删除字符串中的字符'7','8' '54cbaabc9' #转换后的字符串没有字符'7','8'
3.X下的演示过程:
>>> map = str.maketrans('123','abc', '78')#要删除的字符需要在这指定 >>> s = '54321123789' >>> s.translate(map) '54cbaabc9'
我在读《Python Cookbook》遇到了一个基于2.X版本的例子,如下
import string def translator(frm='', to='', delete='', keep=None): if len(to) == 1: to = to * len(frm) trans = string.maketrans(frm, to) if keep is not None: allchars = string.maketrans('', '') delete = allchars.translate(allchars, keep.translate(allchars,delete)) def translate(s): return s.translate(trans, delete) return translate
allchars应该是一个返回的映射表,为什么还可以调用translate方法,所以它应该是一个str类型,测试如下:
>>> import string >>> map = string.maketrans('123', 'abc') >>> type(map) <type 'str'>
在3.X版本中这个方法不能正常通过运行,那么错在什么地方呢,我们看看映射表是什么类型:
>>> map = str.maketrans('123','abc') >>> type(map) <class 'dict'>
知道了映射表的类型了,我们就可以对其进行“后期加工”,像上面《Python Cookbook》中的例子一样,来满足我们的编码要求。
上面讨论的例子用的字符串是ASCII字符组成的,如果是字节类型,2.X版本中操作是一样的,3.X中调用bytes或bytearray的函数;若是unicode类型的,2.X需要用unicode的translate方法,注意下面的代码
>>> print u"hallo".translate({97:u'e'}) hello >>> print u"hallo".translate({'a':u'e'}) hallo >>> print u"hallo".translate({u'a':u'e'}) hallo
结果之所以不一样,查阅手册可知unicode的translate方法的映射表也就是字典的键必须是unicode的位序数,值可以是unicode的位序数、unicode字符串或这None。

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器