python自学第四天,字符串用法

String 的用法

names="张三 welcome {city}"

print(names.capitalize())#首字母大写
print(names.count(""))#统计里面的字符
print(names.center(100,"-"))#打印100个字符,字符串在中间,其它用-来填充 
print(names.encode(encoding="utf-8"))#把字符串转换为字节

print(names.endswith("g"))#判断字符串以什么结尾

print(names.startswith(""))#判断字符串以什么开始
print(names.find("come"))#查找字符串的位置
print(names.index("come"))#find没什么区别,查找字符串的位置
print(names.format(city="chongqing"))#格式化字符串的中{}
print(names.format_map({"city":"chongqing"}))#用字典的形式来格式化
print(names.isdigit())#判断字符是不是数字
print(names.isidentifier())#判断是不是一个合法的变量名
names.islower()#判断是不是小写
names.isupper()#判断是不是大写
print(','.join(['1','2','3']))#列表加入到字符串中
print(names.ljust(50,"*"))#向左边填充* 一共50个字符
print(names.rjust(50,"-"))#向右边填充- 一共50个字符
print(names.lower())#把大写变成小写
print(names.upper())#把小写变成大写
print(names.strip())#两边都去掉空格和换行
print(names.replace("张三","李四"))#替换字符串
print(names.split())#按照什么来分割出来 成为一个列表
print(names.swapcase())#大写变成小写,小写变成大写
str也可以切片直接像列表一样切片[:]
字典 dict
#字典 key-value  ,它是无序的
info={
    'stu001':"张三",
    'stu002':"李四",
    'stu003':"王麻子",
}
#修改
info['stu001']="hunter"
b={
    'stu001':"杨五",
    1:2,
    2:3
}
info.update(b)#表示把两个字典合并,有相同的key值,就修改value
#增加
info['stu004']='jone'
#删除
info.pop('stu001')
del info['stu002']
info.popitem()#最好不用,随机删除一个
#查找
#info['stu003']#不要用这个查询
print(info.get('stu003'))#如果存在就返回,如果不存在就返回none
print('stu004' in info)
print(info)

print(info.items())#把字典转换为列表

#循环
for i in info:
    print(i,info[i])#最好用这种

for k,v in info.items:
print(k,v)#这种效率很低

c=dict.fromkeys([1,6,7],"test")#一改全改 print(c) district={ "chongqing":{ "yongchuan":"beautiful gril!" }, "beijing":{ "chaoyang":"pengziduo" } } print(district.get("chongqing").get("yongchuan")) district.setdefault("xianggang",{"jiulong":"qianduo"})#先去字典中查找看是否有“xianggang”这个key没有, # 如果有就不改,如果没得就新增一个值 print(district)




 



 


 



原文地址:https://www.cnblogs.com/hunterYi/p/8715538.html