Python学习心得第二周-02 字符串、列表、元组、字典

三 字符串

 
#作用:名字,性别,国籍,地址等描述信息

#定义:在单引号双引号三引号内,由一串字符组成
name='egon'

#优先掌握的操作:
#1、按索引取值(正向取+反向取) :只能取
# 倒着取值(了解):注意方向要一致
msg='hello world'
print(msg[0])
print(msg[-1])
View Code
#2、切片:从一个大字符串中切除一个子字符串(顾头不顾尾,步长)
msg='hello world'
print(msg[0:5])
print(msg[4:8:2])
print(msg[0:])
View Code
#3、长度len
msg='hello world'
print(msg[0:])
print(len(msg))
View Code
#4、成员运算in和not in:判断一个子字符串是否存在于一个大字符串中
msg='hello world alex is sb'
print('alex' in msg)
print('egon'  not in msg)
View Code
#5、移除空白strip
msg='***   /// $hello    ***&&&       '
print(msg.strip('*& $/'))
res=msg.strip()
print(res)

name=input('>>>:').strip()  #模拟登录用户输入用户名后误输入“ ”
print(name)
View Code
#6、切分split:把一个字符串按照某种分隔符切成一个列表
info='root:x:0:/root:bin/root'
res=info.split(':')  #以:为分隔符切分
print(res)  #切分后的内容以列表形式显示
print(res[0])    #提取切分后的列表中的第一个内容
res1=info.split(':',3) #以:为分隔符切分,共切分3次
print(res1)


cmd='get a.txt 444'
res=cmd.split()#默认以‘空格’切分
print(res)
View Code
#7、循环for
#循环打印出字符串内容
msg='hello world' #以while形式打印出内容
i=0
while i < len(msg):
    print(msg[i])
    i+=1

msg1='hello world' #以for循环来实现功能,命令少且简洁
for x in msg1:
    print(x)
View Code
for循环也可以实现下述内容
for+break
for+continue
 
#二:该类型总结
# 1 存一个值
#
# 2 有序
#
# 3 不可变

  

需要掌握的操作

#1、strip,lstrip,rstrip
print('*****egon*****'.strip('*'))
print('*****egon*****'.lstrip('*'))
print('*****egon*****'.rstrip('*'))
#2、lower,upper
print('aaAbCCC'.lower())#大写
print('aaAbCCC'.upper())#小写
#3、startswith,endswith
print('alex is sb'.startswith('alex'))#是否以alex开头
print('alex is sb'.endswith('sb'))#是否以alex结尾

True

True

#4、format的三种玩法
print('my name is %s my age is %s' %(18,'egon'))
print('my name is {name} my age is {age}'.format(age=18,name='egon'))#根据定义名传对应的值,无序
print('my name is {} my age is {}'.format(18,'egon'))#按照位置传值,同%s
print('my name is {0}{0}{0} my age is {1}'.format(18,'egon'))#根据索引,多次传特定值
#5、split,rsplit
cmd='get|a.txt|3333'

print(cmd.split('|',1))#以‘|’切分,切分次数为1
print(cmd.rsplit('|',1))#从右往左以‘|’切分,切分次数为1
#6、join
info='root:x:0:/root:bin/root'
res=info.split(':')#先去除分隔符,以列表显示
print(res,type(res))
info1=':'.join(res)#将:再次插入到列表数据中
print(info1)
#7、replace:替换字符串
msg='my name is alex,alex say hello'
print(msg.replace('alex','SB',1))#alex为原值,SB为想替换的新值,修改一次,‘故第二个alex不会被替换’
print(msg)
#8、isdigit:判断字符串内是否是纯数字
print('10123'.isdigit())

#--------------------------------------------------

age_of_db=50
age_of_inp=input('>>>: ').strip() #age_of_inp='sadfsadfasdf'
if age_of_inp.isdigit():
    age_of_inp=int(age_of_inp)
    if age_of_inp > age_of_db:
        print('too big')
    elif age_of_inp < age_of_db:
        print('too small')
    else:
        print('you got it')
else:
    print('必须输入数字啊傻叉')
复制代码
#strip
name='*egon**'
print(name.strip('*'))
print(name.lstrip('*'))
print(name.rstrip('*'))

#lower,upper
name='egon'
print(name.lower())
print(name.upper())

#startswith,endswith
name='alex_SB'
print(name.endswith('SB'))
print(name.startswith('alex'))

#format的三种玩法
res='{} {} {}'.format('egon',18,'male')
res='{1} {0} {1}'.format('egon',18,'male')
res='{name} {age} {sex}'.format(sex='male',name='egon',age=18)

#split
name='root:x:0:0::/root:/bin/bash'
print(name.split(':')) #默认分隔符为空格
name='C:/a/b/c/d.txt' #只想拿到顶级目录
print(name.split('/',1))

name='a|b|c'
print(name.rsplit('|',1)) #从右开始切分

#join
tag=' '
print(tag.join(['egon','say','hello','world'])) #可迭代对象必须都是字符串

#replace
name='alex say :i have one tesla,my name is alex'
print(name.replace('alex','SB',1))

#isdigit:可以判断bytes和unicode类型,是最常用的用于于判断字符是否为"数字"的方法
age=input('>>: ')
print(age.isdigit())
复制代码

 其他操作(了解即可)

#1、find,rfind,index,rindex,count

#2、center,ljust,rjust,zfill
#3、expandtabs
#4、captalize,swapcase,title
#5、is数字系列
#6、is其他
#find,rfind,index,rindex,count
name='egon say hello'
print(name.find('o',1,3)) #1,3顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
# print(name.index('e',2,4)) #同上,但是找不到会报错
print(name.count('e',1,3)) #count 统计次数,顾头不顾尾,如果不指定范围则查找所有

#center,ljust,rjust,zfill
name='egon'
print(name.center(30,'-'))#指定宽度30,不够使用-填充
print(name.ljust(30,'*'))#内容左对齐
print(name.rjust(30,'*'))#内容右对齐
print(name.zfill(50)) #用0填充

#expandtabs:控制按一次tab键代表的空格数
name='egon	hello'
print(name)
print(name.expandtabs(1))

#captalize,swapcase,title
print(name.capitalize()) #首字母大写
print(name.swapcase()) #大小写翻转
msg='egon say hi'
print(msg.title()) #每个单词的首字母大写

#is数字系列
#在python3中
num1=b'4' #bytes
num2=u'4' #unicode,python3中无需加u就是unicode
num3='' #中文数字
num4='' #罗马数字

#isdigt:bytes,unicode
print(num1.isdigit()) #True
print(num2.isdigit()) #True
print(num3.isdigit()) #False
print(num4.isdigit()) #False

#isdecimal:uncicode
#bytes类型无isdecimal方法
print(num2.isdecimal()) #True
print(num3.isdecimal()) #False
print(num4.isdecimal()) #False

#isnumberic:unicode,中文数字,罗马数字
#bytes类型无isnumberic方法
print(num2.isnumeric()) #True
print(num3.isnumeric()) #True
print(num4.isnumeric()) #True

#三者不能判断浮点数
num5='4.3'
print(num5.isdigit())
print(num5.isdecimal())
print(num5.isnumeric())
'''
总结:
    最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景
    如果要判断中文数字或罗马数字,则需要用到isnumeric
'''

#is其他
print('===>')
name='egon123'
print(name.isalnum()) #字符串由字母或数字组成
print(name.isalpha()) #字符串只由字母组成

print(name.isidentifier())
print(name.islower())
print(name.isupper())
print(name.isspace())
print(name.istitle())

    练习   

# 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
name = " aleX"
# 1)    移除 name 变量对应的值两边的空格,并输出处理结果
# 2)    判断 name 变量对应的值是否以 "al" 开头,并输出结果

# 3)    判断 name 变量对应的值是否以 "X" 结尾,并输出结果

# 4)    将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
# 5)    将 name 变量对应的值根据 “l” 分割,并输出结果。
# 6)    将 name 变量对应的值变大写,并输出结果

# 7)    将 name 变量对应的值变小写,并输出结果

# 8)    请输出 name 变量对应的值的第 2 个字符?
# 9)    请输出 name 变量对应的值的前 3 个字符?
# 10)    请输出 name 变量对应的值的后 2 个字符?

# 11)    请输出 name 变量对应的值中 “e” 所在索引位置?

# 12)    获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
# 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
name = " aleX"
# 1)    移除 name 变量对应的值两边的空格,并输出处理结果
name = ' aleX'
a=name.strip()
print(a)

# 2)    判断 name 变量对应的值是否以 "al" 开头,并输出结果
name=' aleX'
if name.startswith(name):
    print(name)
else:
    print('no')

# 3)    判断 name 变量对应的值是否以 "X" 结尾,并输出结果
name=' aleX'
if name.endswith(name):
    print(name)
else:
    print('no')

# 4)    将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
name=' aleX'
print(name.replace('l','p'))

# 5)    将 name 变量对应的值根据 “l” 分割,并输出结果。
name=' aleX'
print(name.split('l'))

# 6)    将 name 变量对应的值变大写,并输出结果
name=' aleX'
print(name.upper())

# 7)    将 name 变量对应的值变小写,并输出结果
name=' aleX'
print(name.lower())

# 8)    请输出 name 变量对应的值的第 2 个字符?
name=' aleX'
print(name[1])

# 9)    请输出 name 变量对应的值的前 3 个字符?
name=' aleX'
print(name[:3])

# 10)    请输出 name 变量对应的值的后 2 个字符?
name=' aleX'
print(name[-2:])

# 11)    请输出 name 变量对应的值中 “e” 所在索引位置?
name=' aleX'
print(name.index('e'))

# 12)    获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
name=' aleX'
a=name[:-1]
print(a)
View Code

四 列表

复制代码
#作用:多个装备,多个爱好,多门课程,多个女朋友等

#定义:[]内可以有多个任意类型的值,逗号分隔
my_girl_friends=['alex','wupeiqi','yuanhao',4,5] #本质my_girl_friends=list([...])
或
l=list('abc')

#优先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可存也可以取      
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in

#5、追加
#6、删除
#7、循环
复制代码
复制代码
#ps:反向步长
l=[1,2,3,4,5,6]

#正向步长
l[0:3:1] #[1, 2, 3]
#反向步长
l[2::-1] #[3, 2, 1]
#列表翻转
l[::-1] #[6, 5, 4, 3, 2, 1]
复制代码

  

    练习:

复制代码
1. 有列表data=['alex',49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量

2. 用列表模拟队列

3. 用列表模拟堆栈

4. 有如下列表,请按照年龄排序(涉及到匿名函数)
l=[
    {'name':'alex','age':84},
    {'name':'oldboy','age':73},
    {'name':'egon','age':18},
]
答案:
l.sort(key=lambda item:item['age'])
print(l)
复制代码

五 元组

复制代码
#作用:存多个值,对比列表来说,元组不可变(是可以当做字典的key的),主要是用来读

#定义:与列表类型比,只不过[]换成()
age=(11,22,33,44,55)本质age=tuple((11,22,33,44,55))

#优先掌握的操作:
#1、按索引取值(正向取+反向取):只能取   
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in

#5、循环
复制代码

  练习

复制代码
#简单购物车,要求如下:
实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
} 
复制代码
msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
goods_l=[]
while True:
    for key,item in msg_dic.items():
        print('name:{name} price:{price}'.format(price=item,name=key))
    choice=input('商品>>: ').strip()
    if not choice or choice not in msg_dic:continue
    count=input('购买个数>>: ').strip()
    if not count.isdigit():continue
    goods_l.append((choice,msg_dic[choice],count))

    print(goods_l)
View Code

六 字典

复制代码
#作用:存多个值,key-value存取,取值速度快

#定义:key必须是不可变类型,value可以是任意类型
info={'name':'egon','age':18,'sex':'male'} #本质info=dict({....})
或
info=dict(name='egon',age=18,sex='male')
或
info=dict([['name','egon'],('age',18)])
或
{}.fromkeys(('name','age','sex'),None)

#优先掌握的操作:
#1、按key存取值:可存可取
#2、长度len
#3、成员运算in和not in

#4、删除
#5、键keys(),值values(),键值对items()
#6、循环
复制代码

  练习

1 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中

即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
a={'k1':[],'k2':[]}
c=[11,22,33,44,55,66,77,88,99,90]
for i in c:
    if i>66:
        a['k1'].append(i)
    else:
        a['k2'].append(i)
print(a)
View Code
2 统计s='hello alex alex say hello sb sb'中每个单词的个数

结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
s='hello alex alex say hello sb sb'

l=s.split()
dic={}
for item in l:
    if item in dic:
        dic[item]+=1
    else:
        dic[item]=1
print(dic)
View Code
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
print(words)
for word in words: #word='alex'
    dic[word]=s.count(word)
    print(dic)


#利用setdefault解决重复赋值
'''
setdefault的功能
1:key存在,则不赋值,key不存在则设置默认值
2:key存在,返回的是key对应的已有的值,key不存在,返回的则是要设置的默认值
d={}
print(d.setdefault('a',1)) #返回1

d={'a':2222}
print(d.setdefault('a',1)) #返回2222
'''
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
for word in words: #word='alex'
    dic.setdefault(word,s.count(word))
    print(dic)



#利用集合,去掉重复,减少循环次数
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
words_set=set(words)
for word in words_set:
    dic[word]=s.count(word)
    print(dic)
其他做法(重点看setdefault的用法)
原文地址:https://www.cnblogs.com/zhutiancheng/p/9261038.html