ใช้ re.match() กับ pattern ^[a-zA-Z0-9]+$ ตัวอย่าง bool(re.match(^[a-zA-Z0-9]+$, 789#%$def)) False
ใช้ re.match() กับ pattern ^[a-zA-Z0-9]+$ ตัวอย่าง bool(re.match(^[a-zA-Z0-9]+$, 789#%$def)) False
1. ใช้ isdigit() 12345a.isdigit() False 2. ใช้ Regex ^[0-9]+$ bool(re.match(^[0-9]+$, 123)) True re.match() คืน match object ต้องแปลงเป็น bool()
1. ใช้ Sets from sets import Set allowed_chars = Set(1234) validationString = 121 if Set(validationString).issubset(allowed_chars): print(True) else: print(False) ผลลัพธ์ True 2. ใช้ Regex ^[1234]+$ bool(re.match(^[1234]+$, 123)) True หมายเหตุ: Regex ต้อง escape ตัวอักษรพิเศษ ใช้ re.escape(
ใช้ isnumeric() สำหรับ unicode strings ตัวอย่าง u1,a234.isnumeric() False แตกต่างจาก isdigit() ที่ทำงานกับ ASCII digits เท่านั้น
1. ใช้ islower() hello world.islower() True 2. ใช้ Regex ^[a-z]+$ bool(re.match(^[a-z]+$, abc)) True
1. ใช้ isupper() HELLO.isupper() True 2. ใช้ Regex ^[A-Z]+$ bool(re.match(^[A-Z]+$, ABC)) True
เนื้อหาไม่สมบูรณ์ มีเพียงส่วนหัวข้อ ใช้ isspace() ตาม ID 1004108101 abc.isspace() False
1. ใช้ isspace() print( .isspace()) True 2. ใช้ Regex ^\s+$ bool(re.match(r^\s+$, )) True
1. ใช้ isupper() print(u.isupper()) False 2. ใช้ range check def check_upper(c): if A <= c <= Z: return True else: return False print(check_upper(A)) # True print(check_upper(a)) # False
1. ใช้ concatenation operator + str1 = Hello str2 = World str3 = str1 + str2 print(str3) # HelloWorld 2. ใช้ str.join(seq) รวมหลายสตริงพร้อม separator s = - seq = (a, b, c) print(s.join(seq)) # a-b-c สตริง s จะกลายเป็น separator ระหว่างแต่ละ element
บทความนี้ซ้ำกับ ID 1004108097 ส่วนแรก ใช้ len() หาจำนวนตัวอักษร print(len(abcdefghijklmnopqrstuvwxyz)) 26
1. ความยาว (จำนวนตัวอักษร): ใช้ len() len(Hello World!) 12 2. ขนาดในหน่วย Bytes: ใช้ sys.getsizeof() getsizeof(Hello World!) 33 getsizeof() รวม overhead ของ object ด้วย
ใช้ ljust(width[, fillchar]) pad ด้านขวา ตัวอย่าง print(Mona Lisa.ljust(12)) print(Mona Lisa.ljust(12, $)) ผลลัพธ์ Mona Lisa Mona Lisa$$$ สำหรับ pad ด้านซ้าย ใช้ rjust() แทน
ใช้เมธอด lower() ตัวอย่าง Jane Doe N.Y..lower() jane doe n.y.
ใช้ lstrip() ตัด whitespace, newline, tab นำหน้า hello world!.lstrip() hello world! ใช้ strip() ตัดทั้งนำและท้าย hello world! .strip() hello world!
ใช้ built-in max() บนสตริง ตัวอย่าง max(stripedzebra) z เปรียบเทียบตาม Unicode code point
ใช้ built-in min() บนสตริง ตัวอย่าง min(TAJMAHAL) A เปรียบเทียบตาม Unicode code point (A-Z < a-z)
ใช้เมธอด replace(old, new) ของ string class ตัวอย่าง chihuahua.replace(hua, hah) chihahhah ใช้ re.sub() สำหรับ pattern ซับซ้อน re.sub(hua, hah, chihuahua) chihahhah
ใช้ rfind() คืน index ของ occurrence สุดท้าย หรือ -1 ตัวอย่าง NikolaTesla.rfind(kola) 2
ใช้ rfind() ค้นหาจากท้ายสตริง คืน index ของ occurrence สุดท้าย หรือ -1 ถ้าไม่เจอ ตัวอย่าง CocacolaPepsi.rfind(coke) -1