python中關於元素替換的一些總結


python中元素進行替換有很多方法,下面是我學習中的一些總結
1、字符串替換str.replace()方法

python中的replace()方法是把字符串中的old字符串替換成new的字符串,如果指定替換次數max,則按照替換次數進行替換

str.replace(old,new,count=0)

old:字符串替換前的字符
new:字符串替換后的字符
count:替換的次數,默認為0,不填表示全局替換

>>> str = "hello world! I love python!"
>>> str.replace("l","@")  # 表示全局替換
'he@@o wor@d! I @ove python!'
>>> str.replace("l","@",2)  # 替換指定次數
'he@@o world! I love python!'
>>> str.replace("l","@",2).replace("o","$")  # 多個字符替換可以進行鏈式調用replace()方法
'he@@$ w$rld! I l$ve pyth$n!'
2、正則表達式中的sub()和subn()方法

sub(pattern, repl, string)
其中pattern表示原字符串中的字符,repl表示需要替換成的字符,string表示需要替換的字符串;
subn()和sub()的區別在於subn()返回的一個包含新字符串和替換次數的二元組;

>>> import re
>>> str = "hello world! I love python!"
>>> re.sub("hello","nihao",str)  
'nihao world! I love python!'
>>> re.subn("l","*",str)
('he**o wor*d! I *ove python!', 4)
>>> 
3、如果同時處理多個字符串的替換,此時可以使用string的maketrans()和translate()方法

maketrans()方法用來生成字符映射表,而translate()方法則按映射表中定義的對應關系轉換並替換其中的字符,用這兩種方法可以同時處理多個不同的字符。

>>> table = ''.maketrans("abcdefghij","1234567890")  # 創建映射表,注意字符串的長度要一致,達到一一對應的目的
>>> str = "hello world! i love python"
>>> str.translate(table)  # 按照關系表將sting中的字符逐個進行替換
'85llo worl4! 9 lov5 pyt8on'
>>> 
4、對列表里的元素進行替換,可以使用列表解析的方法
>>> list = [1,2,3,4]
>>> rep = [5 if x==1 else x for x in list]
>>> rep
[5, 2, 3, 4]
>>> 

批量進行替換

>>> list = [1,2,3,4,5]
>>> pattern = [2,4]
>>> rep = ["a" if x in pattern else x for x in list]
>>> rep
[1, 'a', 3, 'a', 5]
>>> 

根據字典的映射進行替換

>>> list
[1, 2, 3, 4, 5]
>>> dict = {1:"apple", 3:"banana"}
>>> rep = [dict[x] if x in dict else x for x in list]
>>> rep
['apple', 2, 'banana', 4, 5]
>>> 
5、在Python中,字符串屬於不可變對象,不支持原地修改,如果需要修改其中的值,只能重新創建一個新的字符串對象。但是如果一定要修改原字符串,可以使用io.StringIO對象。
>>> from io import StringIO
>>> str = "hello world!" 
>>> io_str = StringIO(str)
>>> io_str
<_io.StringIO object at 0x7fa1e61addc8>
>>> io_str.tell()  # 返回當前的位置
0
>>> io_str.read()  # 從當前位置開始讀取字符串
'hello world!'
>>> io_str.getvalue()  # 返回字符串的全部內容
'hello world!'
>>> io_str.seek(6)  # 定義開始修改的位置
6
>>> io_str.write("china")  # 修改字符串
5
>>> io_str.read()
'!'
>>> io_str.getvalue()  # 獲取修改后的字符串全部內容
'hello china!'
>>> io_str.tell() 
12
>>> 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM