gacvd 发表于 2018-8-15 12:57:49

python - 字符串,元组,列表,字典

# -*- coding: utf-8 -*-  
"""
  
Created on Sat Jan7 13:55:45 2017
  

  
"""
  

  
#----------------------定义一个字符串---------------------------
  
str='abcd    q'
  
print (str)
  
print (str.capitalize())
  
#去除字符串两个空格
  
print (str.strip())
  
#去除字符串左侧的空格
  
print (str.lstrip())
  
#去除字符串右侧的空格
  
print (str.rstrip())
  
#分隔字符并生成列表
  
a = str.split()
  

  
print (a)
  
print (a)
  
#字符串居中显示 默认空格补齐
  
print (str.center(20,'-'    ))
  
#----------------------定义一个列表---------------------------
  
list1 = ['Huawei', 'ALBB', 'Tencent', 'Baidu']
  
#向列表里面追加一个元素
  
list1.append('hehe')
  

  
#向列表特定位置插入一个元素
  
list1.insert(0,'gyh')
  
list1.insert(1,'chh')
  

  
#将列表内部的元素位置翻转
  
list1.reverse()
  
print ("列表反转后: ", list1)
  
#列表内部元素排序
  
list1.sort()
  
print (list1)
  

  
#踢出特定元素
  
list1.remove('Baidu')
  

  
#pop溢出列表内部的元素 默认最后一个元素
  
list2 = ['Huawei', 'ALBB', 'Tencent', 'Baidu','Google']
  
print( "溢出前",list2)
  
list2.pop(0)
  
print ("溢出后",list2)
  
#输出结果为:溢出前 ['Huawei', 'ALBB', 'Tencent', 'Baidu', 'Google'
  
#          溢出后 ['ALBB', 'Tencent', 'Baidu', 'Google']
  

  
#列表的截取
  
#截取全部
  
print (list2[:])
  
#输出结果为:['ALBB', 'Tencent', 'Baidu', 'Google']
  

  
#截取1号元素到结尾
  
print (list2)
  
#输出结果为:['Tencent', 'Baidu', 'Google']
  

  
#截取1-3号之间的元素 不包括3号元素
  
print(list2)
  
#输出结果为:['Tencent', 'Baidu']
  

  
#类列表转化为元组
  
print (tuple(list2))
  
#输出结果为:('ALBB', 'Tencent', 'Baidu', 'Google')
  

  
#extend方法 将一个列表中的元素添加到另一个列表里
  
a=
  
b=
  
b.extend(a)
  
print (b)
  

  

  

  

  
#----------------------定义一个字典---------------------------
  
dict={'name':'gyh','age':25}
  
print (dict)
  

  
#字典的浅复制
  
dict1=dict.copy()
  
print (dict1)
  

  
#清除列表元素
  
dict.clear()
  
print (dict)
  

  
#fromkeys 使用另一个字典内的元素作为key
  
#字典(Dictionary) fromkeys() 函数用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
  
dict2=('name','age','work')
  
dict3={'gyh','25','IT'}
  
dict4={}
  

  
dict4=dict4.fromkeys(dict2,10)
  
print (dict4)
  

  
#字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。
  
dict5={'name':'gyh','age':25}
  
print (dict5.get('name','haha'))
  
print (dict5.get('Name','haha'))
  

  

  
#字典(Dictionary) update() 函数把字典dict2的键/值对更新到dict里
  
dict = {'Name':'Zara','Age':7}
  
dict02 = {'Sex':'female'}
  
dict.update(dict02)
  
print ("Value : %s" %dict)
  
#以上实例输出结果为:
  
#Value:{'Age':7, 'Name':'Zara', 'Sex':'female'}
  

  

  
#格式化输出字符串
  
print ('%s %s'%('hello','world')
页: [1]
查看完整版本: python - 字符串,元组,列表,字典