python常用字符串功能
2021-03-01 01:27
标签:com fill 左右 data 反向 爱我 rip python字符串 拼接 python常用字符串功能 标签:com fill 左右 data 反向 爱我 rip python字符串 拼接 原文地址:https://www.cnblogs.com/aotaot/p/14453707.html2.25 python字符串(13个)
1.以XX开头 (startswith())
v1="我爱我的祖国"
result = v1.startswith("我") #判断是否以“我”开头,如果是返回"true"
print(result) #true
#例
v1=input("请输入户籍所在地")
result = v1.startswith("北京")
if result:
print("北京市民")
else:
print("非北京市民")
2.以XX结尾 (endswith())
#同上
3.判断字符是否为10进制 (isdecimal())
#判断字符串是否为数字
v1 = "123456789"
result = v1.isdecimal()
print(result) #True
4.去除字符串两边的空格 (strip() rstrip()左 lstrip()右)
#()内不加字符为去除左右两边空格
msg = " aaa " #左右有空格
print(msg.strip()) #输出"aaa"没有空格
#()内加字符表示去除左右两端的字符,例("a")
msg = "abccba"
print(msg.strip("a")) #输出bccb
5.字符串变大写 (upper())
msg = "my name is oliver queen"
print(msg.upper()) #输出为MY NAME IS OLIVER QUEEN
6.字符串变小写 (lower())
#同上
7.字符串内容替换 (.replace())
#.replace("字符串准备替换内容","替换内容")
data = "你是个好人"
value = data.replace("好人","坏人")
print(value) #输出你是个坏人
#例
content = input("请输入评论") #sbnnnn草
content = content.replace("草","*")
content = content.replace("sb","**")
print(content) #**nnnn*
8.字符串切割 (.split())
#全切.split("")
data = "aot|root|qq.com"
result = data.split("|") #以"|"为界切开
print(result) #输出[‘aot‘, ‘root‘, ‘qq.com‘]
#部分切.split("",123....)
data = "aot|root|qq.com"
result = data.split("|",1) #以"|"为界切开,只切第一个"|"
print(result) #输出[‘aot‘, ‘root|qq.com‘]
#反向切.rsplit("")
9.字符串拼接 ("".join())
#"连接用字符".join(所连接的列表)
data_list = ["aot","is","Oliver"]
v1 = "_".join(data_list)
print(v1)
10.格式化字符串 (.format())
#赋值
name = "{0}有很多爱好,如{1},{2},{3}"
data = name.format("于大爷","抽烟","喝酒","烫头")
print(data)
#.format("a","b","c"),abc分别代表{0},{1},{2}
name = "{0}有很多爱好,{0}喜欢{1},{2},{3}"
data = name.format("于大爷","抽烟","喝酒","烫头")
print(data)
11.字符串互转字节类型 (.encode() .decode())
data = "奥特"
v1 = data.encode("utf-8")
v2 = data.encode("gbk")
print(v1) #输出b‘\xe5\xa5\xa5\xe7\x89\xb9‘
print(v2) #输出b‘\xb0\xc2\xcc\xd8‘
12.字符串内容居中,居左,居右 (.center() .ljust() .rjudt())
#.center(一共的位数,"所用的符号")
v1 = "老王"
data = v1.center(21,"_") #一共21位,老王居中,其余由"_"补充
print(data) #输出__________老王_________
v1 = "老王"
data = v1.ljust(21,"_") #一共21位,老王居左
print(data) #输出老王___________________
v1 = "老王"
data = v1.rjust(21,"_")
print(data) #输出___________________老王
13.帮助填充0 (.zfill())
#.zfill(一共有多少位)
data = "aot"
v1 = data.zfill(8)
print(v1) #输出00000aot
#主要用于处理2进制数