Python内置的字符串常用操作函数

作者:

在

1、title()函数:将字符串首字母转换为大写,例如:

message = 'I like python'
print(message.title())
#输出:
I Like Python

2、在字符串中加入变量,即f字符串方法,变量在双引号中使用花括号括起来,例如:

first_name = 'lee'
last_name = 'vencent'
full_name = f"my name is {first_name} {last_name}"
print(full_name.title())
#输出:
My Name Is Lee Vencent

3、将字符串左右两端的空格去掉,包括去掉左侧空格lstrip()函数,去掉右侧空格rstrip()函数,去掉左右两侧空格strip()函数,例如:

favorite_language = ' python '
favorite_language.lstrip() #得到'python '
favorite_language.rstrip() #得到' python'
favorite_language.strip() #得到'python'

4、换行\n和tab制表符\t,例如:

message = "my favorite language:\n\tPython\n\tC\n\tJava"
print(message)
#输出:
my favorite language:
     Python
     C
     Java

5、移除字符串前缀removeprefix和后缀removesuffix,例如:

url = 'https://www.baidu.com/index.php'
print(url.removeprefix('https://'))
#输出
www.baidu.com/index.php
print(url.removesuffix('/index.php'))
#输出
http://www.baidu.com

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注