大小写转换
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