Python data types, strings, lists, dictionaries, Ganso, collections, encoding supplements, and more

Source: Internet
Author: User
Tags shallow copy

1. String: ' content ' storage of small amounts of data
Index: Is the subscript is starting from 0

s = ' Python automation learning '
S1 = s[0]
Print (S1) #通过索引找到元素

Slice: is a paragraph, "0:4" Gu Tou disregard tail

s = ' Python automation learning '
#通过切片查找python
S1 = S[0:6]
Print (S1)

Step: Skip to fetch

s = ' Python automation learning '
#通过跳着切片查找
S2 = S[:5:2] #0可以省略
Print (s2)

Inverse direction Value: Must add reverse step-1
s = ' Python automation learning '
#倒着取值必须加反向步长-1
S3 = S[-1:-6:-1]
Print (S3)

String manipulation methods:
. Capitalize () capital letter, other lowercase

s = ' Nxfxxy '
S1=s.capitalize () #新的字符串,
Print (S1)

. Upper () All Caps

s = ' Nxfxxy '
S1 = S.upper ()
Print (S1)

. lower () all lowercase

s = ' Nxfxxy '
S1 = S.lower ()
Print (S1)

Small exercise:
Code = ' Qear '. Upper (). Lower ()
you = input (' >>plese: '). Upper (). Lower ()
If you ==code:
Print (' Yes ')
Else
Print (' No ')

. Swapcase () Case reversal big change small, small big

s = ' Nxfxxy '
S1 = S.swapcase ()
Print (S1)

. title () Each letter capitalized, non-character separated by each word

s = ' Nxfxxy ycq q77*&bai '
A=s.title ()
Print (a) #非字母隔开首字母大写全部

Center Center (), default padding is None

s = ' Nxfxxy '
A =s.center ("&")
Print (a) #居中, length set by itself

What does the. startswith () Start with?

s = ' Nxfxxy '
A = S.startswith (' n ') #以什么开头
Print (a)

What does the. endswith () End with?
s = ' Nxfxxy '
A = S.endswith (' y ') #以什么结尾
Print (a)

. Strip () go can write fill, remove letters, except spaces, tab \ t line break is very useful
s = ' Nxfxxy '

A = S.strip ()
Print (a)

. Lstrip () go to the left.
. Rstrip () go to the right #和上面的一样, no example

. Split () string conversion to list important, set number of cuts

s = ' sss lll ddd ggg eee '
sq = s.split ()
Print (SQ) #相当于字符串转换成列表

The. Join () connects the preceding string with the connector, or it can manipulate the list to convert the list into a string, not a non-string content such as a number
String:
s = ' Sfnxfxxy '
SW = ' + '. Join (s)
Print (SW) # S+f+n+x+f+x+x+y

List:
ll =[' xxx ', ' ddd ', ' 222 ']
L2 = '-'. Join (LL)
Print (L2) # xxx-ddd-222

. replace () to replace

s = ' Sfnxfxxy '
Sq = s.replace (' xx ', ' TT ')
Print (SQ) # Sfnxftty

. Find () to find the index of a string if there's more than one.

s = ' Sfnxfxxy '
Sq = s.find (' F ')
Print (SQ) #4

. Index () If you can't find the error, it's better than find.

s = ' Sfnxfxxy '
Sq = s.index (' F ')
Print (SQ) #4

The. IsDigit () is used to determine whether a string is converted to a number

i = ' 123a '
If I.isdigit ():
i = int (i)
Else
Print (' input error ')

. Isalpha () Character composition judgment

i = ' SDF '
If I.isalpha ():
i = str (i)
Print (' correct ')
Else
Print (' input error ')

. Isalnum () whether there is a character and letter composition to judge
Public methods:
. Len () View length

s= ' SDFSADFASDFASDFADSFADSFDSAFEWTR '
sq = len (s)
Print (SQ) #31

. Count () The number of occurrences of an element

s= ' SDFSADFASDFASDFADSFADSFDSAFEWTR '
Sq = s.count (' s ')
Print (SQ) #7

Formatted output:
. format
%s-%d placeholder

res = ' I'm {} {} year old, hobby {} '. Format (' Egon ', ' Male ')
Print (RES) #我叫egon this year 18 years old, love male

res = ' I call {0} this year {0} years old, hobby {0} '. Format (' Egon ', ' Male ')
Print (RES)

res = ' My name {name} this year {age}, hobby {hobby} '. Format (name= ' Egon ', age=18,hobby= ' male ')
Print (RES)

2, Number: int is used to calculate 1 2 3 ...
i = 3
i = 6
Print (I.bit_length ())

‘‘‘
Binary decimal
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
‘‘‘

3, Bool:true False

4, List: "" lists, storage of various data types container type
Index: A string after being taken out.

Slices: followed by a list

Small exercise:

Li = [111, ' Alex ', ' Wusir ']
Print (li[1])
Print (Li[:4:2])

Additions and deletions to change the search,

Increase
. Append () after adding
L = [' lxf ', ' SDF ', ' pp ', ' SDF ']
L.append (' Gourd doll ')
Print (L)

Insert Insertion

L = [' lxf ', ' SDF ', ' pp ', ' SDF ']

L.insert (1, ' Angels ')
Print (L)

Iterate add:
L = [' lxf ', ' SDF ', ' pp ', ' SDF ']
L.extend (' xxxx ')
Print (L)
See effect: [' lxf ', ' SDF ', ' pp ', ' sdf ', ' x ', ' x ', ' x ', ' X ']

Delete:

Delete by index: Pop
L = [' lxf ', ' SDF ', ' pp ', ' SDF ']
L.pop (0)
Print (L)

Delete by element, remove
L = [' lxf ', ' SDF ', ' pp ', ' SDF ']
L.remove (' pp ')
Print (L)

Clear list: Clear
L = [' lxf ', ' SDF ', ' pp ', ' SDF ']
L.clear ()
Print (L)

Delete List Del
L = [' lxf ', ' SDF ', ' pp ', ' SDF ']
Del l
Print (L)

Delete by index:

L = [' lxf ', ' SDF ', ' pp ', ' SDF ']
Del L[3]
Print (L)

Delete by slice:

L = [' lxf ', ' SDF ', ' pp ', ' SDF ']
Del L[:3]
Print (L)

Change:

Change by index:
L = [' lxf ', ' SDF ', ' pp ', ' SDF ']
l[0]= ' Zookeeper '
Print (L)

To change by slicing:
L = [' lxf ', ' SDF ', ' pp ', ' SDF ', ' DF ']
l[:2]= ' IOPL '
Print (L)

Check:
Search by index:

Follow the biopsy:

L = [' lxf ', ' SDF ', ' pp ', ' SDF ', ' DF ']
For I in L:
Print (i)

Other methods:
Number of counts count occurrences
and length:
L = [1,1,2,3,4,5,76,1,1,6]
Print (L.count (1))
Print (Len (l))

#通过元素找索引
Print (L.index (4))

L2 = [3,2,4,5,6,7,8,10,9]
L2.sort () #从小到大
Print (L2)
L2.sort (reverse=true) #从大倒小
Print (L2)
L2.reverse () #反方向排序
Print (L2)

Nesting of lists:

ll = [1, 2, ' lxf ', ' Wusir ', [' Oldboy ', ' Ycq ', [], ' Taibai ']
ll[2]= Ll[2].upper ()
Print (LL)
Ll[4].append (' goddess ')
Print (LL)

5, Ganso: () A variety of data types, read-only list, only limited subset, grandson can be changed

Tu = (1,2,true,[2,3,4], ' ALSSX ')
For I in Tu:
Print (i)

Tu = (1,2,true,[2,3,4], ' ALSSX ')
#切片, Index
Print (tu[2])
Print (Tu[:4])

6, Dictionary: {} Key value pair key values large amount of data, associated data, query fast, binary search

Key is unique and must be immutable data type: (hash): str bool tuple int:value is any data type

Types of data:
Variable: Dict list set
Container type: List tuple dict set
Immutable: Immutable data type: (Can hash): str bool Tuple int

DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' byc ': [[+]}
Print (DIC)

Additions and deletions to change the search,

Increase
DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
dic[' high '] = 180
Print (DIC)

If there is a key to join the responsible coverage, no responsibility to add
DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
dic[' name '] = 180
Print (DIC)

This is the responsibility of the same, without responsibility to add:
DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
Dic.setdefault (' name ', 180)
Print (DIC)

Delete:, 4 method
Delete by key, equivalent to the index of list
DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
Dic.pop (' name ')
Print (DIC)

Empty dictionary:
DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
Dic.clear ()
Print (DIC)

To delete a dictionary:

DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
Del dic[' age ']
Print (DIC)

Delete Last 3.6 After 3.5 is randomly deleted
DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
Dic.popitem ()
Print (DIC)

Change

DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
dic[' name ']= ' PPP '
Print (DIC)

Update

DIC = {"Name": "Jin", "Age": +, "sex": "Male"}
Dic2 = {"Name": "Alex", "Weight": 75}
Dic2.update (DIC) # adds DIC all key-value pairs (same overlay, no add) to Dic2
Print (DIC2)

Check

DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
dic[' name ']
Print (DIC)
Recommended with this, no error
DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
Dic.get (' name2 ')
Print (DIC)

#keys
DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
#keys () can be converted into a list
Print (Dic.keys ())
Print (List (Dic.keys ()))

#values ()
Print (List (dic.values ()))

#.tiems ()
Print (List (Dic.items ()))

For I in Dic.items ():
Print (i)

Small exercises::

DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
For k,v in Dic.items ():
Print (K,V)

#len () View length
DIC = {' name ': ' Taivai ', ' age ': +, ' hobby ': ' Girl ', ' Alex ': [All-in-all]}
#len
Print (len (DIC))

#fromkeys
Dic1 = Dict.fromkeys (' abc ', [+])
Print (DIC1)

Note: If the list is empty, if the data is to be written, then all the data will be written into

7. Set: Intersection/SET/subtraction/subset of relational data. The de-weight of the list
Unordered non-repeating data types, the elements inside must be hashed, but the collection itself is not hash

Relationship testing: Intersection, subset, set, and difference sets
Go weight (list to go Heavy)

Increase
. add
SS = {' SSS ', ' BBB '}
Ss.add (' DDD ')
Print (ss)

. Update

ss={' eee ', ' eee ', ' DDD '}
Ss.update (' abc ')
Print (ss)

Delete

. remove
ss={' eee ', ' eee ', ' DDD '}
Ss.remove (' DDD ')
Print (ss)

Other collections:
#交集
Set1 = {1,2,3,4,5}
set2= {4,5,6,7,8}
Print (Set1 & Set2)

#并集
Print (Set1 | set2)

#差集
Print (Set1-set2)

Inverse intersection

Print (set1 ^ set2)

Frozenset immutable sets to make the set immutable

s = Frozenset (' Barry ')
S1 = Frozenset ({1,2,3,4})
Print (S,type (s))
Print (S1,type (S1))

8. Data type Supplement

#range can make a list of numbers
For I in Range (1,10,2): #有步长
Print (i)

Attention:
Do not change, list, dictionary size
If there is only one element in the ancestor, and no comma is separated, then his data type is consistent with that element.
Small Data pool: int:-5 ~ 256 the same number all points to a memory address
str:s = ' a ' * 20 is the same memory address, 21 is not possible

Depth copy:
For shallow copy, the first layer creates a new memory address, and from the second level it points to the same memory address, so consistency is maintained for the second layer and the deeper layers.

对于深copy来说,两个是完全独立的,改变任意一个的任何元素(无论多少层),另一个绝对不改变   

9. Code:

Electrical signal 01010101010101010
Computer:
A ' SIIC code 128
7-bit identification of one byte
Upgrade to 8 bits a byte 256 2 of the 8-time Square
00000001 = = = one character
Universal code AH: Unicode includes all countries
16 bytes Represents a character
00000001 00000001 = = 2 of a character 16 Times Square

Change: 4 byte table one character is 32 times
11111111 11111111 11111111 11111111 represents a byte 2 of the 32-time Square
Waste of resources:

Upgrade Utf-8: Minimum 8-bit:
English 8 bit one byte, 00000001
Europe 16 bits Two bytes, 00000001 00000001
Asia 24 bits Three bytes, 00000001 00000001 00000001

Python3 under:
Binary between different encodings is not mutually identifiable
pthon3x STR internal encoding mode is Unicode (memory)
However, the storage, and transport of files cannot be Unicode

Bytes Type: internal encoding (memory) is non-Unicode
S1 = B ' FFFF '
Print (S1,type (S1))

For Chinese:

Python data types, strings, lists, dictionaries, Ganso, collections, encoding supplements, and more

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.