python基础(高级变量)

本文详细介绍了Python编程的基础知识,包括字符串操作、列表管理、元组使用及字典的增删改查等功能,适合初学者快速入门。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

del 关键字,可以将变量从内存中删除

数据类型--->非数字型

字符串

字符串定义:用 " 或者 '

str = "1234676"

str[0] --->取第一个字符

for char in str:

     print(char)

len(str)   --->字符串长度

str.count("abc")  ---->子串出现的次数

str.index("123")  ---->子串第一次出现的索引,没有报错

str.find("123") ----->子串第一次出现的索引,没有返回-1

str.ljust(width,fill)  ---->左对齐输出,width为宽度,fill为位数不足时的替换字符

str.rjust(width,fill) ---->右对齐输出,。。。。

str.center(width,fill) ---->居中对齐,。。。

srt.lstrip()----->去除左空白

str.rstrip()--->去除右空白

str.strip()--->去除空白

str.split()  --->不指定参数,则按照空白切割

"aaa".join(str_list) --->以"aaa"为分隔符,将str_list中的字符串拼接

字符串切片:str[start,end,stap]   --->包含start索引,不包含end索引,stap为步长

首尾可以省略,可以用负数

"012346789"[ : ] --->"012346789"

"012346789"[ 0: ] --->"12346789"

"012346789"[ -1: :-1] --->"987643210"

"012346789"[  : :-1] --->"987643210"

其他方法参考API

列表【list】--->其他语言叫数组(其实更像java的List)并且可以存储不同类型的数据

 

name_list = ["zhangsan","lisi"]

name_list[0]  --->"zhangsan"

name_list.index("lisi") --->1   第一次出现时的索引

name_list.append()  ---->末尾添加

name_list.insert(1,"haha")   ----->在指定位置插入数据,其他数据后移

name_list.extend(temp_list)   ---->将temp_list追加到name_list后边

name_list.remove("zhangsan")  --->删除列表中第一个值为"zhangsan"的元素,如果没有则报错

name_list.pop()  --->删除指定下标元素,不指定则删除最后一个

name_list.clear()  --->清空整个列表

del name_list[1] --->将下标1的元素从内存删除

name_list.count("lisi")  --->指定元素在列表中出现的次数

len(name_list) ----> 函数,返回列表长度

name_list.sort() --->升序排序

name_list.sort(reverse=True) ---->降序排序

name_list.reverse() --->逆序

for my_name in name_list:

      print("名字:%s" % my_name)

元组【tuple】,与列表类似,但元素不能修改

info_tuple = ("zhangsan",18,1.80)

info_tuple = ()  --->定义空元组

info_tuple = (6,) ---->定义一个元素的元组,info_tuple = (6) 此时为int类型

info_tuple[0] ---->取元组中下标为0的元素

info_typle.index("zhangsan") ----->取对应值第一次出现时的索引

info_tuple.count("zhangsan")   ---->统计元素的个数

同样可以使用for遍历

for my_info in info_tuple:

    print(my_info)

格式化输出,%后边就是元组

info_tuple = ("zhangsan",18)

print("我的名字是%s,年龄是%d" % info_tuple)

info_str = "我的名字是%s,年龄是%d" % info_tuple

print(info_str) # 效果是一样的

list(元组)---->元组转列表

tuple(列表)---->列表转元组

字典【dictionary】(类似java中的map)

xiaoming_dict = {"name":"小明",

                     "age":18,

                     "height":1.80}

xiaoming_dict["age"] --->取值

xiaoming_dict["weight"]=70 ---->增加键值对

xiaoming_dict["age"]=10  ---->修改

xiaoming_dict.pop("age") ---->删除age的键值对

xiaoming_dict.update(temp_dict) ---->存在的键值对更新,不存在的新增

xiaoming_dict.clear() -->清空字典

for _key in xiaoming_dict: # _key为遍历获取到的键 

      print(_key)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值