Thao tác chuỗi

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Chuyển đổi chữ hoa/thường

my_string = "tHis Is a niCe StriNg"
  • Chuyển thành chữ thường
print(my_string.lower())
this is a nice string
  • Chuyển thành chữ hoa
print(my_string.upper())
THIS IS A NICE STRING
Regular Expressions in Python

 

my_string = "tHis Is a niCe StriNg"

 

  • Viết hoa ký tự đầu
print(my_string.capitalize())
This is a nice string
Regular Expressions in Python

Tách chuỗi (split)

my_string = "This string will be split"
  • Tách chuỗi thành list các chuỗi con
my_string.split(sep=" ", maxsplit=2)
['This', 'string', 'will be split']
my_string.rsplit(sep=" ", maxsplit=2)
['This string will', 'be', 'split']
Regular Expressions in Python

 

my_string = "This string will be split\nin two"

print(my_string)
This string will be split
in two

Regular Expressions in Python
  • Tách theo ranh giới dòng
my_string = "This string will be split\nin two"

 

my_string.splitlines()
['This string will be split', 'in two']
Regular Expressions in Python

Ghép chuỗi (join)

  • Nối chuỗi từ list hoặc iterable khác

 

my_list = ["this", "would", "be", "a", "string"]
print(" ".join(my_list))
this would be a string
Regular Expressions in Python

Xóa ký tự (strip)

  • Xóa ký tự ở hai đầu: .strip()

 

my_string = " This string will be stripped\n"
my_string.strip()
'This string will be stripped'
Regular Expressions in Python

 

my_string = " This string will be stripped\n"
  • Xóa ký tự ở cuối (phải)
my_string.rstrip()
' This string will be stripped'
  • Xóa ký tự ở đầu (trái)
my_string.lstrip()
'This string will be stripped\n'
Regular Expressions in Python

Ayo berlatih!

Regular Expressions in Python

Preparing Video For Download...