ปัญหา
คุณต้องการค้นหาและแทนที่รูปแบบข้อความในสตริง
หากเรามีรูปแบบตัวอักษรที่เรียบง่าย การใช้เมธอด str.replace() จะเป็นทางออกที่ดีที่สุด
ตัวอย่าง
def sample():
yield 'Is'
yield 'USA'
yield 'Colder'
yield 'Than'
yield 'Canada?'
text = ' '.join(sample())
print(f"Output \n {text}") ผลลัพธ์
Is USA Colder Than Canada?
ให้เราดูวิธีค้นหาข้อความก่อน
# search for exact text
print(f"Output \n {text == 'USA'}") ผลลัพธ์
False
เราสามารถค้นหาข้อความโดยใช้วิธีการสตริงพื้นฐาน เช่น str.find(), str.endswith(), str.startswith()
# text start with
print(f"Output \n {text.startswith('Is')}") ผลลัพธ์
True
# text ends with
print(f"Output \n {text.startswith('Is')}") ผลลัพธ์
True
# search text with find
print(f"Output \n {text.find('USA')}") ผลลัพธ์
3
หากข้อความที่ป้อนเพื่อค้นหามีความซับซ้อนมากขึ้น เราก็สามารถใช้นิพจน์ทั่วไปและโมดูล re ได้
# Let us create a date in string format date1 = '22/10/2020'
# Let us check if the text has more than 1 digit.
# \d+ - match one or more digits
import re
if re.match(r'\d+/\d+/\d+', date1):
print('yes')
else:
print('no')
yes ตอนนี้กลับมาแทนที่ข้อความ หากข้อความและสตริงที่จะแทนที่เป็นเรื่องง่าย ให้ใช้ str.replace()
ผลลัพธ์
print(f"Output \n {text.replace('USA', 'Australia')}") ผลลัพธ์
Is Australia Colder Than Canada?
หากมีรูปแบบที่ซับซ้อนในการค้นหาและแทนที่ เราสามารถใช้ประโยชน์จากวิธีการย่อย () ในโมดูลใหม่ได้
อาร์กิวเมนต์แรกของ sub() คือรูปแบบที่จะจับคู่ และอาร์กิวเมนต์ที่สองคือรูปแบบการแทนที่
ในตัวอย่างด้านล่าง เราจะพบฟิลด์วันที่ในรูปแบบ dd/mm/yyyy และแทนที่ในรูปแบบ - yyyy-dd-mm.Backslashed digits เช่น \3 หมายถึงหมายเลขกลุ่มจับในรูปแบบ
import re
sentence = 'Date is 22/11/2020. Tommorow is 23/11/2020.'
# sentence
replaced_text = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', sentence)
print(f"Output \n {replaced_text}") ผลลัพธ์
Date is 2020-22-11. Tommorow is 2020-23-11.
อีกวิธีหนึ่งคือการรวบรวมนิพจน์ก่อนเพื่อให้ได้ประสิทธิภาพที่ดีขึ้น
ผลลัพธ์
pattern = re.compile(r'(\d+)/(\d+)/(\d+)')
replaced_pattern = pattern.sub(r'\3-\1-\2', sentence)
print(f"Output \n {replaced_pattern}") ผลลัพธ์
Date is 2020-22-11. Tommorow is 2020-23-11.
re.subn() จะให้จำนวนการแทนที่พร้อมกับการแทนที่ข้อความกับเรา
ผลลัพธ์
output, count = pattern.subn(r'\3-\1-\2', sentence)
print(f"Output \n {output}") ผลลัพธ์
Date is 2020-22-11. Tommorow is 2020-23-11.
ผลลัพธ์
print(f"Output \n {count}") ผลลัพธ์
2