Python Basic Data type operation

Source: Internet
Author: User

Python comments

当行注视:# 被注释内容
多行注释:""" 被注释内容 """

String manipulation

# represents a single-line comment
s="Hello"
Print (s*2)#hellohello
Print (s[2:])# Llo, slice operation, cut from subscript 2 to last
PrintAIn s)#False

A=' 123 '
b=' ABC '
C=a+b#字符串拼接, poor efficiency, not recommended
#内置方法 join () high efficiency, advancing use
D='----'. Join ([A, b])# 123----ABC,


st="Hello\t kitty {name} is {age}"
St.count (' L ')#统计个数
Print (St.capitalize ())#首字母大写 Hell
Print (St.center (50,‘-‘))#放到中心, 50 Delegates '
#-----------HEllo Kitty {name} i
Print (St.ljust (50,‘-‘))#居左 HEllo
Print (St.rjust (50,‘-‘))#居右-------

Print (St.endswith (' Y '))#以什么结尾
Print (St.startswith (' He '))#以什么开头

Print (St.find (' V '))#查找第一个元素的索引, not for--

Print (St.format (name=' Alex ', age=37)
Print (St.format_map ({' Name ':' Alex ',
Print' 2 '. IsDigit ())#是否为整数
#print (St.index (' QQQ ')) #查找第一个元素的索引没
Print' abc456# '. Isalnum ())#是否是数字跟字符
Print' abc '. ISALPHA ())#是否为字母
Print' 123 '. Isdecimal ())#是否为十进制, basically not
Print' 1234 '. IsNumeric ())#是否为整数
Print' AsdA '. Islower ())#是否为小写
Print' AsdA '. Isupper ())#是否为大写
Print"". Isspace ())#是否是空格 (one or more)
Print ' Abn Av '. Istitle ()) #每一个首字母是否大
print (St.lower ()) #所有大写变小写
print (St.upper ()) #所有小写变大写
Print ( ' AB '. Swapcase ()) #大写变小写, lowercase to uppercase  
print (   AAA   a\nbbb\n. Strip ()) #
St.lstrip () #去左                     
St.rstrip () #去右                     
print ( ' ASADFG '. Replace ( ' a ', ' one ', 1))
print ( ' 2234562 '. RFind ( ' 2 ')) #从右开始找, return
print ( ' a b C '. Split ( ')) #字符串的变为列表 *
print ( ' a b C '. Rsplit ( ", 1)) #从右开始有几
print ( ' AA BA cs '. Title ()) #将首字母都变为大写

List operations

A = ["Xiaohu","Sanpang","Jinxin","Daling","Xiaoguo"]
#查
Print (a[1])
Print (a[1:4])#切片取, before the package
Print (a[1:])#取到最后
Print (a[1:-1])#取到倒数第二个
Print (a[1::2])#步长为2个, the step has direction
Print (a[3::-2]) #步长为2个, Step has direction
print (a[-2:: -1])   #-= Countdown

#增 Insert Append
A.insert ( 1, "Xiaowang")

#修改
a[ 1]= "AAA"
a[ 1: 3]=[ "ss ", " ww "]


#删除remove pop del
A.remove (" Xiaohu ") #只能删一个对象
B=a.pop ( 0) #返回删除的结果
del a[ 3] #可删任何东西, including a object
#count计算列表里元素出现的次数
t = [ "a", "A", "B"].count ( "a")

Merge
a=[ 1, 2, 3]
b=[ 4, 5, 6]
A.extend (b) #a改变了, b unchanged
C=a+b #a, B does not change
print (A.index ( 1)) #返回第一个数据的值

Invert
A.reverse ()
Sort
A.sort ()
Print ( "AA"   in a)

Tuple operations

查询
tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );

print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]

不允许修改元组,但我们可以对元组进行连接组合,如下实例:
tup1 = (12, 34.56);
tup2 = (‘abc‘, ‘xyz‘);

# 创建一个新的元组
tup3 = tup1 + tup2;
print tup3;

删除元组
元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:
tup = (‘physics‘, ‘chemistry‘, 1997, 2000);
del tup;

Dictionary operations

#python中唯一的映射类型------Dictionary (unordered) is stored according to the hash algorithm
#id () #打印内存地址
#不可变类型: Shaping, string, tuple
#可变类型: List, dictionary
#字典的键必须为不可变类型, because it's the only
dict={' Name ':' Zhangqiye ',' Age ':' 11 ',' Sex ':' Nan '}
Print (dict[' Name '])
dict1={}
dict1[' Name ']=' Sanpang ' #可增加, can be modified

Dict1.setdefault (' Name ',' Wangwu ') #只可增加, can not be modified, there is a return value (return value in the dictionary)
Dict1.setdefault (' Age ',' 11 ')
print (dict. keys ()) #dict_keys ([ ' name ',   ' age ',   ' sex '])
print ( Dict. values ()) #dict_values ([ ' Zhangqiye ',   ' one ', '   ' nan '])
print (Dict. items ()) #dict_items ([( ' name ',   ' Zhangqiye '), ( ' age ',   ' one ') ', ( ' sex '),   ' nan ')]
dict2={ 1: 2, : +}
Dict1. Update (DICT2)
print (dict1) #{ ' name ':   ' Sanpang ',   ' age ':   ' 11 ',   1:  2,  22:  "
#删除  del  clear   pop
Del dict[ ' name '
#dict. pop ( ' name ') #有返回值
Dict.clear ()
#dict. Popitem () #随机删除

Collection operations

#作用: de-weight, relational operations,

#定义:
Review of Knowledge points
mutable types are notHash type
Immutable types are availableHash type
#定义集合:
Collection: Can contain multiple elements, separated by commas,
The elements of a collection follow three principles:
1: Each element must be of immutable type (can behash, which can be used as a dictionary key)
2: No duplicate elements
3: Unordered
Note that the purpose of a collection is to store different values together, and to do relational operations between different sets, without having to tangle with individual values in the collection
#set把不同的元素集合在一起 (not the same) unordered, Frozenset immutable collection, which can be traversed with a for, iterator, and in to determine whether the element is in the collection
L = [' Zhang ',' Wang ',' Zhang ']
s =Set' Alex Li ')
S1 =Set (L)
Print (s)#{', ' a ', ' X ', ' l ', ' e ', ' I '}
Print (S1)#{' Wang ', ' Zhang '}
PrintType (S1))#<class ' Set ' > type represents the types of data

Li = [(),' AA ', 1]
SS =Set (LI)
Print (ss) #{(1, 2), 1, ' AA '}
Ss.add (78)#增一个元素
Ss.update ("NMK")#增三个元素
Print (ss) #{(1, 2), 1, +, ' m ', ' n ', ' k ', ' AA '}
Ss.remove (1)#删除
AA = Ss.pop ()#删除, and a clear

Print (set ("qwer") = = Set ("Qwerewq"))#true
Print (set ("Qwer") < set ("Qwer"))#false子集
A = set ([1,2,3,4,5])
b = set ([4,5,6,7,8])
AA = A.intersection (b)#交集
Print (AA) #{4, 5}
Print (A.union (b))#并集 {1, 2, 3, 4, 5, 6, 7, 8}
Print (A.difference (b))#差集 {1, 2, 3}
Print (A.symmetric_difference (b))#对称差集 {1, 2, 3, 6, 7, 8}
The following wording is equivalent to the above, more simple
A|b #并集
A&b# Intersection
A-B#差集
A^b #对称差集

#父级a是b的父级 >
A.issuperset (b)
#子集 <
A.issubset (b)

Python Basic Data type operation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.