Python全栈之路:string字符串常用方法

大小写转换

print("name is Alex".capitalize())  # 转为首字母大写 ->Name is alex
print("name is Alex".title())  # 转为标题形式 ->Name Is Alex
print("Name".upper())   # 转大写 ->NAME
print("Name".lower())   # 转小写 ->name
print("Name".swapcase())  # 交换大小写 ->aLEX

字符串判断

print("name is Alex".startswith("name"))  # 以...开头 ->True
print("name is Alex".endswith("Alex"))  # 以...结尾 ->True
print("123abc".isalnum())  # 字母或数字 ->True
print("abc".isalpha())  # 字母 ->True
print("123".isdigit())  # 数字 ->True
print("123".isnumeric())  # 数字 ->True
print("abc".isidentifier())  # 判断是否为合法变量名 ->True
print(" ".isspace())  # 空格 ->True
print("My Name Is Tom".istitle())  # 标题 ->True
print("My Name Is Tom".isprintable())  # 可打印 tty file, drive file ->True
print("MY".isupper())  # 大写 ->True
print("my".islower())  # 小写 ->True

输出显示

print(",".join(["1", "2", "3"]))  # 连接
#  ->1,2,3
print("name is Alex".split())  # 拆分为列表,默认拆分符为空格
#  ->['name', 'is', 'Alex']
print("name\n is\r\n Alex".splitlines())  # 拆分为列表,默认拆分符为回车
#  ->['name', ' is', ' Alex']
print("name".center(50, "-"))  # 内容居中,两侧填充
# ->-----------------------name-----------------------
print("name".ljust(50, "*"))  # 内容靠左,以*填充
# ->name**********************************************
print("name".rjust(50, "-"))  # 内容靠右,以-填充
# ->----------------------------------------------name
print("name".zfill(50))  # 内容靠右,以0填充
# ->0000000000000000000000000000000000000000000000name
print("name is\t Alex".expandtabs(tabsize=20))  # 设置'\t'宽度
# ->name is              Alex
print("I am from {city},and {year} years old".format(city="Wuhan", year=23))  # 格式化
# ->I am from Wuhan,and 23 years old
print("I am from {city},and {year} years old".format_map({"city": "Wuhan", "year": 23}))  # 字典参数格式化
# ->I am from Wuhan,and 23 years old
print("\nname".lstrip())  # 去除左侧回车和空格 ->name
print("name\n".rstrip())  # 去除右侧回车和空格 ->name
print("    name\n".strip())  # 去除两侧回车和空格 ->name
print("---")

查找替换

p = str.maketrans("abc", "123")  # 创造翻译字典
print(type(p))  # -><class 'dict'>
print("abc".translate(p))  # 翻译,参数:dict ->123
print("name is Tom".replace("n", "N"))  # 替换 ->Name is Tom
print("name is Alix".count("i"))  # 字符计数 ->2
print("name is Alex".find("e"))  # 查找,返回下标,没有则返回-1 ->3
print("name is Alex".rfind("e"))  # 右边开始查找 ->10
print("name is Alex".index("e"))  # 返回索引,不存在则报错 ->3
print("name is Alex".rindex("e"))  # 右边开始查找 ->10

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
评论

打赏作者

彭世瑜

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值