Python字符串处理举例

# 字符串格式化
str = "1+2={},2的平方是{}"
print(str.format(3, 4))  # 1+2=3,2的平方是4
str = "1+2={1},2的平方是{0}"  # 指定下标
print(str.format(4, 3))  # 1+2=3,2的平方是4
dict = {"three": 3, "four": 4}  # 通过字典设置参数
str = "1+2={three},2的平方是{four}"  # 指定变量名
print(str.format(**dict))  # 1+2=3,2的平方是4
print("{:,}".format(123456789))  # 123,456,789
print("{:.2f}".format(3.1415926))  # 3.14 保留2位小数

# f-字符串 语法糖
print(f"1+2={1 + 2},2的平方是{2 * 2}")  # 1+2=3,2的平方是4
print(f"这是一个{{大括号}}")  # 这是一个{大括号}

# 切片
myStr = "我是好人"
print(myStr[0])  #
print(myStr[0:3])  # 我是好

# 统计与寻找下标值
str = "上海自来水来自海上"
print(str.count(""))  # 2
print(str.count("", 0, 5))  # 1 指定范围找
print(str.find(""))  # 1
print(str.rfind(""))  # 7 从右往左找
print(str.find(""))  # -1 找不到返回-1,index找不到会报错

# 字符串替换
str = "hello world!"
print(str.replace("hello", "hi"))  # hi world!
table = str.maketrans("abcde", "ABCDE")  # 定义替换关系表格
print(str.translate(table))  # hEllo worlD!  根据替换关系进行替换

# 首字母判断
if str.startswith(("a", "b", "h")):  # 元组入参,匹配其中一个即可
    print(True)  # True

# 去除
str.strip()  # 去除左右留白
str.removeprefix("hello")  # 去除前缀
str.removesuffix("world!")  # 去除后缀

# 字符串分割
str = "www.baidu.com"
print(str.split("."))  # ['www', 'baidu', 'com']
print(str.split())  # ['www.baidu.com'] 返回一个列表

# jion拼接字符串
str = ".".join(["www", "baidu", "com"])
print(str)  # www.baidu.com
print("".join(["hello", " ", "world"]))  # hello world

# 转义符
print(r"d:\a\b")
print("d:\\a\\b")
print('\"let\\a\\b\"')

"""
d:\a\b
d:\a\b
"let\a\b"
"""

# 超长换行\n
print("abcd\
efg")
"""
abcdefg
"""

print("abc\n" * 2)
""" #长字符串
abc
abc
"""

 

posted @ 2023-01-09 09:58  星瑞  阅读(58)  评论(0编辑  收藏  举报