Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การดึงตัวเลขนำหน้า (Numeric Prefix) จากสตริงใน Python

สมมติว่ามีสตริงที่ขึ้นต้นด้วยตัวเลข บทความนี้จะแสดงวิธีดึงเฉพาะส่วนตัวเลขนำหน้าออกมา

วิธีที่ 1: ใช้ itertools.takewhile และ str.isdigit

ฟังก์ชัน takewhile จะดึงสมาชิกต่อเนื่องจากต้นสตริงตราบใดที่เงื่อนไข str.isdigit เป็นจริง (คือเป็นตัวเลข)

ตัวอย่าง

from itertools import takewhile

stringA = "347Hello"
print("Given string:", stringA)

res = ''.join(takewhile(str.isdigit, stringA))
print("Numeric Prefix from the string:\n", res)

ผลลัพธ์

Given string: 347Hello
Numeric Prefix from the string: 347

วิธีที่ 2: ใช้ re.sub (Regular Expression)

ใช้ regex pattern \D.* แทนที่ตัวอักษรที่ไม่ใช่ตัวเลข (\D) และทุกอย่างหลังจากนั้น (.*) ด้วยสตริงว่าง

ตัวอย่าง

import re

stringA = "347Hello"
print("Given string:", stringA)

res = re.sub(r'\D.*', '', stringA)
print("Numeric Prefix from the string:\n", res)

ผลลัพธ์

Given string: 347Hello
Numeric Prefix from the string: 347

วิธีที่ 3: ใช้ re.findall

ใช้ pattern \d+ หาตัวเลขติดกัน 1 ตัวขึ้นไป แล้วนำมา join

ตัวอย่าง

import re

stringA = "347Hello"
print("Given string:", stringA)

res = ''.join(re.findall(r'\d+', stringA))
print("Numeric Prefix from the string:\n", res)

ผลลัพธ์

Given string: 347Hello
Numeric Prefix from the string: 347

ทั้ง 3 วิธีให้ผลลัพธ์เดียวกัน วิธี regex เร็วและกระชับกว่า ส่วน takewhile เข้าใจง่ายสำหรับมือใหม่