字符串操作

Python 中的正则表达式

Maria Eugenia Inzaugarat

Data Scientist

调整大小写

my_string = "tHis Is a niCe StriNg"
  • 转为小写
print(my_string.lower())
this is a nice string
  • 转为大写
print(my_string.upper())
THIS IS A NICE STRING
Python 中的正则表达式

 

my_string = "tHis Is a niCe StriNg"

 

  • 首字母大写
print(my_string.capitalize())
This is a nice string
Python 中的正则表达式

拆分

my_string = "This string will be split"
  • 将字符串拆分为子串列表
my_string.split(sep=" ", maxsplit=2)
['This', 'string', 'will be split']
my_string.rsplit(sep=" ", maxsplit=2)
['This string will', 'be', 'split']
Python 中的正则表达式

 

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

print(my_string)
This string will be split
in two

Python 中的正则表达式
  • 按行边界断开
my_string = "This string will be split\nin two"

 

my_string.splitlines()
['This string will be split', 'in two']
Python 中的正则表达式

连接(join)

  • 连接列表或其他可迭代对象中的字符串

 

my_list = ["this", "would", "be", "a", "string"]
print(" ".join(my_list))
this would be a string
Python 中的正则表达式

去除字符

  • 从左右两端去除字符:.strip()

 

my_string = " This string will be stripped\n"
my_string.strip()
'This string will be stripped'
Python 中的正则表达式

 

my_string = " This string will be stripped\n"
  • 从右端去除字符
my_string.rstrip()
' This string will be stripped'
  • 从左端去除字符
my_string.lstrip()
'This string will be stripped\n'
Python 中的正则表达式

Ayo berlatih!

Python 中的正则表达式

Preparing Video For Download...