数字加法和字符串加法:
soarli@soarli:~/Desktop$ ipython3
Python 3.6.8 (default, Oct 7 2019, 12:59:55)
Type "copyright", "credits" or "license" for more information.
IPython 5.5.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: a = "lao"
In [2]: b = "wang"
In [3]: c = "zhang"
In [4]: d = a + b
In [5]: d
Out[5]: 'laowang'
In [6]: A = 100
In [7]: B = 200
In [8]: C = A+B
In [9]: C
Out[9]: 300
还可以这样写:
In [10]: e = "===" + a + b + "==="
In [11]: e
Out[11]: '===laowang==='
In [12]: f = "===%s==="%(a+b)
In [13]: f
Out[13]: '===laowang==='
字符串的索引(正向递增&&逆向递减)
In [14]: name = "soarli"
In [15]: name[0]
Out[15]: 's'
In [16]: name[1]
Out[16]: 'o'
In [17]: name[2]
Out[17]: 'a'
In [18]: name[5]
Out[18]: 'i'
In [19]: name[-1]
Out[19]: 'i'
In [20]: name[-2]
Out[20]: 'l'
In [21]: name[-3]
Out[21]: 'r'
In [22]: name[len(name)-1]
Out[22]: 'i'
In [23]: name[6]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-23-1ff7b59960ab> in <module>()
----> 1 name[6]
IndexError: string index out of range
字符串的切片(取到终点前一位)
In [24]: name[2:5]
Out[24]: 'arl'
In [25]: name[2:6]
Out[25]: 'arli'
In [27]: name[2:]
Out[27]: 'arli'
In [28]: name[2:-1]
Out[28]: 'arl'
In [29]: name[2:6:2]
Out[29]: 'al'
In [30]: name[0:]
Out[30]: 'soarli'
In [31]: name[-1:]
Out[31]: 'i'
In [32]: name[-1:0]
Out[32]: ''
In [33]: name[-1:0:-1]
Out[33]: 'ilrao'
In [34]: name[-1::-1]
Out[34]: 'ilraos'
In [35]: name[::-1]
Out[35]: 'ilraos'
字符串的基本操作
In [38]: mystr
Out[38]: 'hello world nice to meet you'
#从左边开始寻找并返回搜索字符串的首字母下标,若不存在返回-1
In [39]: mystr.find("world")
Out[39]: 6
In [40]: mystr.find("to")
Out[40]: 17
In [41]: mystr.find("soarli")
Out[41]: -1
#搜索出现的次数
In [47]: mystr.count("world")
Out[47]: 1
In [48]: mystr.count("o")
Out[48]: 4
In [49]: mystr.count("soarli")
Out[49]: 0
#字符串的替换(原字符串不会被改变,可以通过第三个参数控制替换次数)
In [50]: mystr.replace("world","WORLD")
Out[50]: 'hello WORLD nice to meet you'
In [51]: mystr
Out[51]: 'hello world nice to meet you'
In [52]: mystr.replace("o","xxxxxxx")
Out[52]: 'hellxxxxxxx wxxxxxxxrld nice txxxxxxx meet yxxxxxxxu'
In [53]: mystr.replace("o","xxxxxxx",2)
Out[53]: 'hellxxxxxxx wxxxxxxxrld nice to meet you'
#字符串的切割
In [54]: mystr.split(" ")
Out[54]: ['hello', 'world', 'nice', 'to', 'meet', 'you']
#首字母大写
In [55]: mystr.capitalize()
Out[55]: 'Hello world nice to meet you'
In [57]: mystr.title()
Out[57]: 'Hello World Nice To Meet You'
#判断字符串末/首字符
In [58]: file_name = "xxxx.txt"
In [59]: file_name.endswith(".txt")
Out[59]: True
In [61]: name_2 = "wang xxxxx"
In [62]: name_2.startswith("wang")
Out[62]: True
#大小写转换
In [63]: exit_confirm = "YeS"
In [64]: exit_confirm.lower()
Out[64]: 'yes'
In [65]: exit_confirm.upper()
Out[65]: 'YES'
#输出格式控制
In [67]: deer = "想要陪你一起看大海"
In [68]: deer.center(50)
Out[68]: ' 想要陪你一起看大海 '
In [69]: deer.ljust(50)
Out[69]: '想要陪你一起看大海 '
In [70]: deer.rjust(50)
Out[70]: ' 想要陪你一起看大海'
#去除多余空格
In [74]: deer_2 = " 想要陪你一起看大海 "
In [76]: deer_2.strip()
Out[76]: '想要陪你一起看大海'
In [93]: test
Out[93]: ' 132 '
In [94]: test.split()
Out[94]: ['132']
#分割成元组(rpartition可以从右边查找)
In [101]: mystr
Out[101]: 'hello world nice to meet you'
In [102]: mystr.partition("nice")
Out[102]: ('hello world ', 'nice', ' to meet you')
#按换行符生成列表
In [103]: test = "hello\nworld\nnice\nto\nmeet\nyou"
In [104]: print(test)
hello
world
nice
to
meet
you
In [105]: test.split()
Out[105]: ['hello', 'world', 'nice', 'to', 'meet', 'you']
#判断输入是数字还是字母(可用于密码安全性检验)
In [109]: num = input()
123
In [110]: num.isalpha()
Out[110]: False
In [111]: num.isdigit()
Out[111]: True
In [112]: num.isalnum()
Out[112]: True
In [113]: num = input()
a
In [114]: num.isalpha()
Out[114]: True
In [115]: num.isdigit()
Out[115]: False
In [116]: num.isalnum()
Out[116]: True
In [117]: num = input()
123abc
In [118]: num.isalpha()
Out[118]: False
In [119]: num.isdigit()
Out[119]: False
In [120]: num.isalnum()
Out[120]: True
#判断是否为纯空格
In [121]: num = input()
123abc
In [122]: num.isspace()
Out[122]: False
In [123]: num = input()
123 abc
In [124]: num.isspace()
Out[124]: False
In [127]: num = input()
In [128]: num.isspace()
Out[128]: True
#使用join将列表转换为字符串
In [129]: a = ["aaa","bbb","cccc"]
In [130]: b = "="
In [131]: b.join(a)
Out[131]: 'aaa=bbb=cccc'
In [132]: b = " "
In [133]: b.join(a)
Out[133]: 'aaa bbb cccc'
In [134]: b = ""
In [135]: b.join(a)
Out[135]: 'aaabbbcccc'
#练习:去除字符串里面的空格和\t
In [136]: a = "das g f d\t hy \t ua id\ths f ka \td s ih dsai fgu a\twfgw"
In [137]: result = a.split()
In [138]: result
Out[138]:
['das',
'g',
'f',
'd',
'hy',
'ua',
'id',
'hs',
'f',
'ka',
'd',
's',
'ih',
'dsai',
'fgu',
'a',
'wfgw']
In [139]: " ".join(result)
Out[139]: 'das g f d hy ua id hs f ka d s ih dsai fgu a wfgw'
In [140]: "".join(result)
Out[140]: 'dasgfdhyuaidhsfkadsihdsaifguawfgw'
列表的增删改查
增:
添加新的元素
append()
insert()
extend()
soarli@soarli:~/Desktop$ ipython3
Python 3.6.8 (default, Oct 7 2019, 12:59:55)
Type "copyright", "credits" or "license" for more information.
IPython 5.5.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: names = ['老王','老李','老刘']
In [2]: names
Out[2]: ['老王', '老李', '老刘']
In [3]: names.append("老赵")
In [4]: names
Out[4]: ['老王', '老李', '老刘', '老赵']
In [5]: #append默认添加到列表的最后
In [6]: #names.insert(位置,要添加的内容)
In [7]: names.insert(0,"八戒")
In [8]: names
Out[8]: ['八戒', '老王', '老李', '老刘', '老赵']
In [10]: names.insert(2,"沙僧")
In [11]: names
Out[11]: ['八戒', '老王', '沙僧', '老李', '老刘', '老赵']
In [12]: names2 = ["葫芦娃","叮当猫","猴子"]
In [13]: names2
Out[13]: ['葫芦娃', '叮当猫', '猴子']
In [14]: names3 = names + names2
In [15]: names3
Out[15]: ['八戒', '老王', '沙僧', '老李', '老刘', '老赵', '葫芦娃', '叮当猫', '猴子']
In [17]: names2
Out[17]: ['葫芦娃', '叮当猫', '猴子']
In [18]: names.extend(names3)
In [19]: names
Out[19]:
['八戒',
'老王',
'沙僧',
'老李',
'老刘',
'老赵',
'八戒',
'老王',
'沙僧',
'老李',
'老刘',
'老赵',
'葫芦娃',
'叮当猫',
'猴子']
In [20]: #因此,我们可以使用extend来合并列表
列表中append和extend的区别
#append不管是什么类型,直接将其整体加上;extend仅适用于列表的合并
In [1]: a = [11,22,33]
In [2]: b = [11,22,33]
In [3]: c = [44,55]
In [4]: a.append(c)
In [5]: a
Out[5]: [11, 22, 33, [44, 55]]
In [6]: b.extend(c)
In [7]: b
Out[7]: [11, 22, 33, 44, 55]
注意a.append(b)就表示将b加入a中,不要写成a = a.append(b),否则会将a赋值为None。
删:
删除元素:
pop()------------>删除最后一个
remove()--------->根据内容删除
del xxxx[下标]--->根据下标删除
In [21]: names
Out[21]:
['八戒',
'老王',
'沙僧',
'老李',
'老刘',
'老赵',
'八戒',
'老王',
'沙僧',
'老李',
'老刘',
'老赵',
'葫芦娃',
'叮当猫',
'猴子']
In [22]: names.pop()
Out[22]: '猴子'
In [23]: names
Out[23]:
['八戒',
'老王',
'沙僧',
'老李',
'老刘',
'老赵',
'八戒',
'老王',
'沙僧',
'老李',
'老刘',
'老赵',
'葫芦娃',
'叮当猫']
In [24]: #pop把最后一个删除
In [25]: names.remove("老王")
In [26]: names
Out[26]:
['八戒',
'沙僧',
'老李',
'老刘',
'老赵',
'八戒',
'老王',
'沙僧',
'老李',
'老刘',
'老赵',
'葫芦娃',
'叮当猫']
In [27]: #从头开始搜索,只删除一个
In [28]: #列表类似于字符串,可以使用切片和索引
In [29]: names[0]
Out[29]: '八戒'
In [30]: names[2:5]
Out[30]: ['老李', '老刘', '老赵']
In [31]: names
Out[31]:
['八戒',
'沙僧',
'老李',
'老刘',
'老赵',
'八戒',
'老王',
'沙僧',
'老李',
'老刘',
'老赵',
'葫芦娃',
'叮当猫']
In [32]: del names[0]
In [33]: names
Out[33]: ['沙僧', '老李', '老刘', '老赵', '八戒', '老王', '沙僧', '老李', '老刘', '老赵', '葫芦娃', '叮当猫']
改:
修改:
xxxx[下标] = new值
In [34]: names[0]
Out[34]: '沙僧'
In [35]: names[0] = "沙师弟"
In [36]: names
Out[36]: ['沙师弟', '老李', '老刘', '老赵', '八戒', '老王', '沙僧', '老李', '老刘', '老赵', '葫芦娃', '叮当猫']
查:
查询:
in
not in
In [37]: if "老赵" in names:
...: print("找到了...")
...:
找到了...
In [38]: if "老赵" not in names:
...: print("可以添加老赵")
...:
小程序:名字管理系统(谨慎输入,无异常处理功能)
#1. 打印功能提示
print("="*50)
print(" 名字关系系统 V1.0")
print(" 1:添加一个新的名字")
print(" 2:删除一个名字")
print(" 3:修改一个名字")
print(" 4:查询一个名字")
print(" 5:退出系统")
print("="*50)
names = []#定义一个空的列表用来存储添加的名字
while True:
#2. 获取用的选择
num = int(input("请输入功能序号:"))
#3. 根据用户的选择,执行相应的功能
if num==1:
new_name = input("请输入要添加的名字:")
names.append(new_name)
print(names)
elif num==2:
del_name = input("请输入要删除的名字:")
names.remove(del_name)
print(names)
elif num==3:
print(names)
cgnm_name = eval(input("请输入要替换名字的下标(从0开始):"))
cgvalue = input("请输入要替换的名字:")
names[cgnm_name] = cgvalue
print(names)
elif num==4:
find_name = input("请输入要查询的名字:")
if find_name in names:
print("找到了你要找的人")
else:
print("查无此人")
elif num==5:
break
else:
print("您的输入有误,请重新输入")
字典的基本操作
In [35]: banzhang = ["班长","山东",18]
In [36]: print("%s %d %s"%(banzhang[0],banzhang[2],banzhang[1]))
班长 18 山东
In [37]: #当有较多数据时,使用列表极不方便,容易出错
In [38]: #字典的引入
In [39]: #infor = {键:值,键:值}
In [40]: infor = {"name":"班长","addr":"山东","age":18}
In [41]: print("%s %s %d"%(infor["name"],infor["addr"],infor["age"]))
班长 山东 18
#优势:使用键代替下表方便索引
小程序:名片管理系统(部分功能待续)
#1. 打印功能提示
print("="*50)
print(" 名片管理系统 V0.01")
print(" 1. 添加一个新的名片")
print(" 2. 删除一个名片")
print(" 3. 修改一个名片")
print(" 4. 查询一个名片")
print(" 5. 显示所有的名片")
print(" 6. 退出系统")
print("="*50)
#用来存储名片
card_infors = []
while True:
#2. 获取用户的输入
num = int(input("请输入操作序号:"))
#3. 根据用户的数据执行相应的功能
if num==1:
new_name = input("请输入新的名字:")
new_qq = input("请输入新的QQ:")
new_weixin = input("请输入新的微信:")
new_addr = input("请输入新的住址:")
#定义一个新的字典,用来存储一个新的名片
new_infor = {}
new_infor['name'] = new_name
new_infor['qq'] = new_qq
new_infor['weixin'] = new_weixin
new_infor['addr'] = new_addr
#将一个字典,添加到列表中
card_infors.append(new_infor)
print(card_infors)
elif num==2:
pass
elif num==3:
pass
elif num==4:
pass
elif num==5:
print("姓名\tQQ\t微信\t住址")
for temp in card_infors:
print("%s\t%s\t%s\t%s"%(temp['name'], temp['qq'], temp['weixin'], temp['addr']))
elif num==6:
break
else:
print("输入有误,请重新输入")
print("")
字典的增删改查
添加:
xxx[新的key] = value
删除:
del xxx[key]
修改:
xxx[已存在的key] = new_value
xxx.get(key)
In [1]: infor = {"name"}
#直接新建
In [2]: infor = {"name":"banzhang"}
In [3]: infor["age"] = 18
In [4]: infor
Out[4]: {'age': 18, 'name': 'banzhang'}
In [5]: infor["QQ"] = 10086
In [6]: infor
Out[6]: {'QQ': 10086, 'age': 18, 'name': 'banzhang'}
In [7]: infor["QQ"] = 10010 #可以直接修改
In [8]: infor
Out[8]: {'QQ': 10010, 'age': 18, 'name': 'banzhang'}
#删除键值对
In [9]: del infor['QQ']
In [10]: infor
Out[10]: {'age': 18, 'name': 'banzhang'}
In [11]: infor['name']
Out[11]: 'banzhang'
In [12]: infor['age']
Out[12]: 18
#用该种方法查找不存在的键,程序会出现异常,可用.get方法判断是否存在(存在则会返回值的信息,不存在返回空白)
In [13]: infor['QQ']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-13-1a3df48c595a> in <module>()
----> 1 infor['QQ']
KeyError: 'QQ'
In [14]: infor.get("name")
Out[14]: 'banzhang'
In [15]: infor.get("age")
Out[15]: 18
In [16]: infor.get("QQ")
In [17]: infor.get("sex")
列表的遍历:
nums = [11,22,33,44,55]
#nums_len = len(nums)
#i = 0
#while i < nums_len:
# print(nums[i])
# i += 1
for num in nums:
print(num)
#相比于while,for更简洁
for ... else...结构(仅限于python)
#只要for循环没有被中途退出(break),else的语句便会被执行
ls = [11,22,33,44,55]
for i in ls:
print(i)
#break
else:
print("=========")
#可用于下列情景
card_infors = [{"name":"laowang","age":18},{"name":"laoli","age":19},{"name":"laozhao","age":20}]
find_name = input("请输入要查找的名字:")
#用此方法可以代替flag(状态判断标志)
for temp in card_infors:
if temp['name'] == find_name:
print("找到了")
break
else:
print("没有找到")
"""
执行效果:
soarli@soarli:~/Desktop$ python3 3.py
请输入要查找的名字:laowang
找到了
soarli@soarli:~/Desktop$ python3 3.py
请输入要查找的名字:laoli
找到了
soarli@soarli:~/Desktop$ python3 3.py
请输入要查找的名字:laozhao
找到了
soarli@soarli:~/Desktop$ python3 3.py
请输入要查找的名字:laoliu
没有找到
"""
字典的常见操作和遍历
In [1]: infor = {"name":"laowang","age":18}
In [2]: len(infor)
Out[2]: 2
In [3]: #len输出键值对的个数
In [4]: infor.keys()
Out[4]: dict_keys(['name', 'age'])
In [5]: infor.values()
Out[5]: dict_values(['laowang', 18])
In [6]: for temp in infor.keys():
...: print(temp)
...:
name
age
In [7]: for temp in infor.values():
...: print(temp)
...:
laowang
18
In [8]: infor.items()
Out[8]: dict_items([('name', 'laowang'), ('age', 18)])
In [9]: #得到了key和value被封装的一个元组
In [10]: for temp in infor.items():
...: print(temp)
...:
('name', 'laowang')
('age', 18)
In [11]: #我们可以通过下标将其取出来
In [12]: for temp in infor.items():
...: print("key=%s,value=%s"%(temp[0],temp[1]))
...:
key=name,value=laowang
key=age,value=18
#换一种方法
In [13]: a = (11,22)
In [14]: b = a
In [15]: b
Out[15]: (11, 22)
In [16]: c,d = a
In [17]: c
Out[17]: 11
In [18]: d
Out[18]: 22
In [19]: #上述c,d从a的产生过程叫做拆包
In [20]: #由此原理,我们可以更加方便的取出items中的键值
In [21]: for A,B in infor.items():
...: print("key=%s,value=%s"%(A,B))
...:
key=name,value=laowang
key=age,value=18
字典和列表的使用场景
一般情况下,若要存放一种数据类型,我们选用列表;如果是多种,我们选用字典。
元组:只能查看(包括遍历),不能修改
In [1]: num = (11,22,33)
In [2]: type(num)
Out[2]: tuple
In [3]: num[1]
Out[3]: 22
In [4]: num[1] = 123
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-eb772b407033> in <module>()
----> 1 num[1] = 123
TypeError: 'tuple' object does not support item assignment
列表、字典、集合、元组的相互转换(转自知乎)
1. 列表与元组的互换
# 将列表转化为元组
li = [1, 2, 3]
t = tuple(li)
print(t, type(t))
# 打印结果:(1, 2, 3) <class 'tuple'>
# 将元组转换成列表
tu = (1, 2, 3)
li = list(tu)
print(li, type(li))
# 打印结果:[1, 2, 3] <class 'list'>
2. 列表与字符串的互换
# 列表转换成字符串
li = ['人', '生', '苦', '短']
str1 = ''.join(li)
print(str1, type(str1))
# 输出结果:人生苦短 <class 'str'>
# 字符串转换成列表
str2 = 'hello python'
li1 = str2.split(' ')
print(li1, type(li1))
# 输出结果:['hello', 'python'] <class 'list'>
3. 列表与字典转换
# 列表转字典方式一
list1 = ['name', 'age', 'sex']
list2 = ['张三', 18, '男']
dict = {}
for i in range(len(list1)):
dict[list1[i]] = list2[i]
print(dict, type(dict))
# 输出结果:{'name': '张三', 'age': 18, 'sex': '男'} <class 'dict'>
# 列表转字典方式二:使用内置函数zip
list1 = ['name', 'age', 'sex']
list2 = ['张三', 18, '男']
d = dict(zip(list1, list2))
print(d)
# 字典转换成列表
dict = {'name': '张三', 'age': 18, 'sex': '男'}
keys = list(dict.keys())
values = list(dict.values())
print(keys, type(keys))
print(values, type(values))
4.嵌套列表转字典
list3 = [['key1','value1'],['key2','value2'],['key3','value3']]
print(dict(list3))
5. 列表与集合转换
# 列表转集合
list1 = [1, 3, 4, 3, 2, 1]
s1 = set(list1)
print(s1, type(s1))
# 输出结果:{1, 2, 3, 4} <class 'set'>
# 集合转列表
list2 = list(s1.intersection(s1))
print(list2, type(list2))
# 输出结果:[1, 2, 3, 4] <class 'list'>
6. 元组和字符串转换
# 元组转换成字符串和列表方法一样
# 字符串转换成元组,需要将字符串转换成列表,在利用列表转成元组
list = []
a = '人生苦短'
list.append(a)
print(list)
b = tuple(list)
print(b, type(b))
# 输出结果:('人生苦短',) <class 'tuple'>
7.元组和字典转换
# 字典转元组
dict = {'name': 'xiaoming', 'age': 18}
tup = tuple(dict)
print(tup) # 只转换了key
tup2 = tuple(dict.values())
print(tup2)
# 元组不能转成字典
8.字典和字符串转换
# 字典转换为字符串
dic1 = {'a': 1, 'b': 2}
str1 = str(dic1)
# 输出结果:{'a': 1, 'b': 2} <class 'str'>
# 字符串转字典
dic2 = eval("{'name':'xiaoming', 'age':18}")
print(dic2, type(dic2))
9.字符串和集合转换
# 字符串转集合
str1 = 'hello'
s1 = set(str1)
print(s1, type(s1))
# 输出结果:{'e', 'o', 'h', 'l'} <class 'set'>
10.字典key和value值转换
dic1 = {'a': 1, 'b': 2, 'c': 3}
dic2 = {value: key for key, value in dic1.items()}
print(dic2)
参考资料:
https://zhuanlan.zhihu.com/p/82703713
版权属于:soarli
本文链接:https://blog.soarli.top/archives/53.html
转载时须注明出处及本声明。