python - แทนที่อักขระหลายตัวด้วยอักขระเดียว [ซ้ำกัน]

ฉันกำลังมองหาวิธีแทนที่อักขระบางตัวด้วยอักขระอื่น

ตัวอย่างเช่น เรามี:

chars_to_be_replaced = "ihgr"

และเราต้องการให้พวกเขาถูกแทนที่ด้วย

new_char = "ข"

เพื่อให้เกิดสตริงใหม่

s = "ฉันหิว"

กลายเป็น

s' = "บีเอ็ม บันบี้"

ฉันทราบดีว่าคุณสามารถทำเช่นนี้ได้ทีละตัวอักษรด้วย .replace หรือนิพจน์ทั่วไป แต่ฉันกำลังมองหาวิธีที่จะผ่านสตริงเพียงครั้งเดียว

re.sub ผ่านไปเพียงครั้งเดียวผ่านสตริงหรือไม่ มีวิธีอื่นในการทำเช่นนี้หรือไม่? ขอบคุณ

ขอบคุณ


person Pierre L.    schedule 27.06.2017    source แหล่งที่มา
comment
ไม่ต้องใช้ความพยายาม   -  person Fallenhero    schedule 27.06.2017
comment
string.replace() ใช้งานไม่ได้สำหรับคุณอย่างไร   -  person Drako    schedule 27.06.2017
comment
ด้วยการแทนที่คุณต้องผ่านสตริงสำหรับอักขระแต่ละตัวที่คุณต้องการลบใช่ไหม   -  person Pierre L.    schedule 27.06.2017
comment
ไม่คุณทำไม่ได้ import re; re.sub("[ihgr]", "b", "im hungry")   -  person Eric Duminil    schedule 27.06.2017
comment
นั่นไม่ใช่ .replace()   -  person Pierre L.    schedule 27.06.2017


คำตอบ (2)


คุณสามารถใช้ string.translate()

from string import maketrans

chars_to_be_replaced = "ihgr"
new_char = "b"
s = "im hungry"

trantab = maketrans(chars_to_be_replaced, new_char * len(chars_to_be_replaced))

print s.translate(trantab)
# bm bunbby
person Ghilas BELHADJ    schedule 27.06.2017

เป็นอย่างไรบ้าง:

chars_to_be_replaced = "ihgr"
new_char = "b"

my_dict = {k: new_char for k in chars_to_be_replaced}

s = "im hungry"

new_s = ''.join(my_dict.get(x, x) for x in s)
print(new_s)  # bm bunbby

''.join(my_dict.get(x, x) for x in s): สำหรับตัวอักษรแต่ละตัวในสตริงต้นฉบับของคุณ ตัวอักษรจะพยายามรับค่าพจนานุกรมแทน ยกเว้นในกรณีที่ไม่มีตัวอักษรต้นฉบับจะถูกส่งกลับ


หมายเหตุ: คุณสามารถเร่งความเร็วได้ (เล็กน้อย) โดยส่ง list ถึง join แทนตัวสร้าง:

new_s = ''.join([my_dict.get(x, x) for x in s])
person Ma0    schedule 27.06.2017
comment
ฉันได้ทำการทดสอบกับตัวอย่างเล็กๆ นี้เท่านั้น แต่ต้องใช้เวลามากกว่าการใช้การแทนที่สี่ครั้ง จำเป็นต้องใช้มันกับตัวอย่างที่เป็นตัวแทนเพิ่มเติม - person Pierre L.; 27.06.2017