"Python3 basic data type, basic operation"

Source: Internet
Author: User
Tags delete key shallow copy

Tag: Width bit identifies SDE SLA intersect end Kanji parameter

I. Basic data type 1. String

Class: Str

Method: Select str, hold command (CTRL) + Left button to jump to the corresponding method

    • Create
A = "hexin" a = str (' hexin ')
    • Transformation
Age = 19new_age = str (age)
    • Concatenation of strings
name = ' hexin ' gender = ' female ' NEW_STR = name + genderprint (NEW_STR)

    • String formatting placeholders
# name = ' My name is Li Jie, sex:%s, I'm%s this year, I'm lying! ' # NEW_STR = name% (' man ', ' + ') # print (NEW_STR) name = ' My name is Li Jie, gender:%s, I'm%s this year, I'm lying! '% (' male ', ', ') print (name)

Determines whether a subsequence is in it

Content = "123 days ago to Thailand to play girl, accidentally contracted the disease, his inner activity is, really should come a few more" if "a few days ago to" in Content:print (' contains sensitive characters ') else:print (content)

    • removing blank Strip
A = '   he xin  ' Print (a) New_a=a.strip ()    #左右new_a1 =a.lstrip ()       #左new_a2 =a.rstrip () #右print (new_a) print (NEW_A1) print (NEW_A2)

Output

   He xin  He xinhe Xin     he xin
    • Segmentation
User_info = "Ex|in s123 9" v1 = user_info.split (' | ') V2 = user_info.split (' | ', 1) v3 = User_info.rsplit (", 1) print (v1) print (v2) print (v3)

Output

[' Ex ', ' in s123 9 '] [' Ex ', ' in s123 9 '] [' Ex|in s123 ', ' 9 ']

    • Length Len ()
User_info = "Ex|in s123 9" v1 = Len (user_info) print (v1)

Output

12

    • Index
val = "Exin" v = Val[0]print (v) val = input (' >>> ') i = 0while i < Len (val):    print (val[i])    i + = 1

Output

E>>>iiiiii

    • Slice
name = ' My name Li Jie, gender I'm a year old, I'm lying! ' Print (name[0]) print (Name[0:2]) print (Name[5:9]) print (name[5:]) print (name[5:-2]) print (name[-2:])

Output

I am my name sex I am this year old, I am lying! Sex I'm a year old, I'm lying!

The usual methods of string are summarized as follows:

    • 1) Capitalize

Function: Implement the first letter of the string, not change itself, will generate a new value

Example:

1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 name = ' Hexin ' 4 v = name.capitalize () #调用str类, execute the method where capitalize is 5 print (v)

Output:

Hexinhexin

    • 2) Casefold

Function: Turn all uppercase letters into lowercase, and support multiple language changes in addition

Example:

1 name = ' Hexin ' 2 v = name.casefold () 3 print (name) 4 print (v)

Output:

Hexinhexin

    • 3) Lower,upper

Function:

Lower: lowercase all caps, limited English

Upper: Capitalize all lowercase

Lower

Example:

1 name = ' Hexin ' 2 v = name.lower () 3 print (name) 4 print (v)

Results:

Hexinhexin

    • 4) Center

Function: text centered, padding character in white space

Parameter 1: Total length, Parameter 2: space-filled characters (length 1)

Center

Example:

1 name = ' Hexin ' 2 v = name.center (' * ') 3 print (name) 4 print (v)

Output:

hexin*******hexin********

    • 5) Count

Function: Indicates the number of occurrences of a subsequence to find in a string

Parameter 1: The value to find (sub-sequence), Parameter 2: Start position (index), parameter 3: End position (index)

Count

Example:

1 name = ' HEXINDDAKLFJSL;DFJCNLJDAJSFLAJDF ' 2 v = name.count (' a ') 3 i = Name.count (' A ', 0,15) 4 print (name) 5 print (v) 6 print (i )

Output:

31

    • 6) EndsWith

Function: Judge whether to end with XX

Parameter 1: Judging value, Parameter 2, 3: Position of start and end (number)

EndsWith

Example:

1 name = ' HEXINDDAKLFJSL;DFJCNLJDAJSFLAJDF ' 2 v = name.endswith (' df ') 3 i = Name.endswith (' n ', 0,5) 4 print (name) 5 print (v) 6 p Rint (i)

Output:

Hexinddaklfjsl;dfjcnljdajsflajdftruetrue

    • 7) Expandtabs

function: Find tab \ t, replace (with previous value)

Expandtabs

Example:

1 name = "AL\TE\TX\NALEX\TUU\TKKK" 2 v = name.expandtabs (5)  #包含前面的值, 5 length 3 print (v)

Output:

Al   e    xalex uu   KKK

    • 8) Find

Function: Find the index position of the specified subsequence, there is no return-1

Find

Example:

1 name = ' Hexin ' 2 v = name.find (' 0 ') 3 i = Name.find (' x ') 4 print (v) 5 print (i)

Output:

-12

    • 9) Format,%s,format_map

Function: String formatting

Format

Format_map

Example:

1 TPL1 = "I am:%s; age:%s; Gender:%s"% (  ' Hexin ', ' m ', ' man ') 2 print (TPL1) 3  4 tpl2 = "I am: {0}; Age: {1}; Gender: {2}" 5 v2 = Tpl2.format ("Li Jie", 19, ' All Lines ') 6 print (v2) 7  8 TPL3 = "I am: {name}; Age: {Gender}" 9 V3 = Tpl3.format (name= ' Li Jie ', age=19,gender= ' random ') print (v3) All Tpl4 = "I am: {nam e}; Ages: {Age}; Gender: {gender} "V4 = Tpl4.format_map ({' name ': ' Li Jie ', '": ' ", ' gender ': ' In '} ') print (v4)

Output:

I am: hexin; age: 18; Gender: Man I am: Li Jie; age: 19; Sex: All Right I am: Li Jie; age: 19; Sex: Casual I am: Li Jie; age: 19; Gender: Middle

    • ) isalnum

Function: Whether it is a number or a Chinese character

Isalnum

Example:

1 name = ' Hexin0 good ' 2 v = name.isalnum () 3 print (v)

Output:

True

    • One) isdecimal,isdigit,isnumeric

Function: Whether it is a number

Isalnumisdecimalisdigit

Example:

1 num = ' two ' 2 V1 = num.isdecimal () # ' 123 ' 3 v2 = Num.isdigit ()   # ' 123 ', ' ② ' 4 v3 = num.isnumeric () # ' 123 ', ' two ', ' ② ' 5 print (V1,V2,V3)

Output:

False False True

    • Isidentifer)

Function: Whether it is a valid identifier

Isidentifier

Example:

1 n = ' 1name ' 2 u = ' name ' 3 v = n.isidentifier () 4 i = U.isidentifier () 5 print (v) 6 print (i)

Output:

Falsetrue

    • Islower (Isupper)

function: all lowercase (uppercase)

Islower

Example:

1 name = ' Hexin ' 2 name1 = ' hexin ' 3 v = name.islower () 4 i = Name1.islower () 5 print (v) 6 print (i)

Output:

TrueFalse

    • isprintable)

Function: Contains implied XX (False for invisible characters including \n,\t)

Isprintable

Example:

1 name = ' Hexindas\talj,hexin ' 2 v = name.isprintable () 3 print (v)

Output:

False

    • ) Join

Function: Element stitching

Join

Example:

1 name = ' Hexin ' 2 3 v = "_". Join (name) # inner loop each element 4 print (v) 5 6 name_list = [' 1 ', ' 2 ', ' 3 ', ' 4 ']7 v = "+". Join (name_list) 8 pri NT (v)

Output:

H_e_x_i_n1+2+3+4

    • Rjust,ljust)

Function: Fill left and right, like center

Ljust

Example:

1 name = ' Hexin ' 2 v = name.ljust (+, ' * ') 3 i = Name.rjust (6, ' * ') 4 print (v) 5 print (i)

Output

Hexin**********hexin

    • Maketrans,translate)

Function: Create correspondence, translate transformations

Maketrans

Example:

1 m = Str.maketrans (' Aeiou ', ' 12345 ') # correspondence 2 name = "AKPSOJFASDUFASDLKFJ8AUSDFAKJSDFL;KJER09ASDF" 3 v = name.translate (m) 4 Print (v)

Output:

1kps4jf1sd5f1sdlkfj815sdf1kjsdfl;kj2r091sdf

    • ) partition

Function: Split, preserve split elements

Partition

Example:

1 content = "9sb6sb6" 2 v = content.partition (' SB ') # Partition3 print (v)

Output:

(' 9 ', ' SB ', ' 6sb6 ')

    • +) Replace

function: Replace

Replace

Example:

1 content = "1SB2SB3SB4" 2 v = content.replace (' sb ', ' Love ') 3 print (v) 4 v = content.replace (' sb ', ' Love ', 1) 5 print (v)

Output:

1love2love3love41love2sb3sb4

    • Strip)

Features: Remove whitespace, \n,\t, custom

Strip

Example:

1 name = ' hexin \ t ' 2 v = name.strip () # blank, \n,\t3 print (v)

Output:

Hexin

    • ) Zfill

Function: Fill 0

Zfill

Example:

1 name = ' Hexin ' 2 v = name.zfill (3) print (v)

Output:

000000000000000hexin

2. Integer

class int

    • 1) bit_length

Function: The minimum number of digits for the binary representation of the current integer

Bit_length

Example:

Age = 4 # 100print (Age.bit_length ())

Output:

3

    • 2) To_bytes

Function: Gets the byte representation of the current data

To_bytes

Example:

Age = 15v = Age.to_bytes (10,byteorder= ' big ') v = age.to_bytes (10,byteorder= ' little ') print (v)

Output:

B ' \x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00 '

3.list List

Class List

Variable type

    • Create
A = [' dog ', ' eric ', 123]a = List ([' Dog ', ' Eric ', 123]) print (a)

Output

[' Dog ', ' Eric ', 123]

    • In judging
A = [' dog ', ' Eric ', 123]if ' Eric ' in A:    print (True) print (a)

Output

true[' dog ', ' Eric ', 123]

    • Index
val = a[0]

    • Length
val = Len (a)

    • Slice
A = [' dog ', ' eric ', 123]v = A[0::2]print (v)

Output

[' Dog ', 123]

Add:

    • 1) Append

Function: Append

Append

Example:

User_list = [' Tom ', ' Liu ', ' Jack ', ' n '] # variable type user_list.append (' Hex ') print (user_list)

Output

[' Tom ', ' Liu ', ' Jack ', ' n ', ' hex ']

    • 2) Clear

Function: Empty

Example:

User_list = [' Tom ', ' Liu ', ' Jack ', ' n '] # variable type user_list.clear () print (user_list)

Output:

[]

    • 3) Copy

function: Shallow copy

Example:

User_list = [' Tom ', ' Liu ', ' Jack ', ' n '] t = user_list.copy () print (user_list) print (t)

Output:

[' Tom ', ' Liu ', ' Jack ', ' n '] [' Tom ', ' Liu ', ' Jack ', ' n ']

    • 4) Count

Function: Count

Example:

User_list = [' Tom ', ' N ', ' Liu ', ' Jack ', ' n ', ' n ']t = User_list.count (' n ') print (user_list) print (t)

Output:

[' Tom ', ' N ', ' Liu ', ' Jack ', ' n ', ' n ']3

    • 5) Extend

Features: Extending the original list

Example:

User_list = [' Tom ', ' N ', ' Liu ', ' Jack ', ' n ', ' n ']user_list.extend (' 9 ') print (user_list)

Output:

[' Tom ', ' N ', ' Liu ', ' Jack ', ' n ', ' n ', ' 9 ']

    • 6) Index

Function: Find element index, no error

Example:

User_list = [' Tom ', ' N ', ' Liu ', ' Jack ', ' n ', ' n ']v = User_list.index (' n ') print (v)

Output:

1

    • 7) Pop

Function: Delete and get elements, index

Example:

User_list = [' Tom ', ' N ', ' Liu ', ' Jack ', ' n ', ' n ']v = user_list.pop (1) print (v) print (user_list)

Output:

n[' Tom ', ' Liu ', ' Jack ', ' n ', ' n '

    • 8) Remove

Function: Delete, value

Example:

User_list = [' Tom ', ' N ', ' Liu ', ' Jack ', ' n ', ' n ']user_list.remove (' n ') print (user_list)

Output:

[' Tom ', ' Liu ', ' Jack ', ' n ', ' n ']

    • 9) Reverse

Function: Flip

Example:

User_list = [' Tom ', ' N ', ' Liu ', ' Jack ', ' n ', ' n ']user_list.reverse () print (user_list)

Output:

[' n ', ' n ', ' Jack ', ' Liu ', ' N ', ' Tom ']

    • ) sort

Function: Sort

Example:

num = [11,2,3,6,111]num.sort () print (num) num.sort (reverse=true) print (num)

Output:

[2, 3, 6, 11, 111] [111, 11, 6, 3, 2]

4.range
    • 1) Create

py2.7: Generate numbers now

Range (1,11) # Generate 1,23,,4,56.10

Py3: Will not be generated immediately, only the loop iteration, only one generation;

For I in Range (1,11):     print (i) for J in Range (1,11,2):     print (j) for K in range (10,0,-1):     print (k)
123456789101357910987654321

Example

# li = [' Eric ', ' Alex ', ' Tony ']
# for I in range (0,len (LI)):
# ele = li[i]
# Print (ele)


Li = [' Eric ', ' Alex ', ' Tony ']
For I in Li:
Print (i)

# for I in range (0,len (LI)):
# print (I+1,li[i])

Output

Ericalextony
5.enumerate

Function: Generate an extra column of sequential numbers

Example

Li = [' Eric ', ' Alex ', ' Tony ']for I,ele in Enumerate (li,1):    print (I,ele) #1 eric#2 alex#3 Tony
Li = [' Eric ', ' Alex ', ' Tony ']for I,ele in Enumerate (li,1):    print (i,ele) v = input (' Please enter product serial number: ') v = Int (v) item = Li[v-1]pri NT (item) #1 eric#2 alex#3 tony# Please enter the product serial number: 1#eric

6.tuple tuples

Cannot be modified, son cannot be modified, grandson can

    • 1) Create
User_tuple = (' Hex ', ' Eric ', ' Seven ', ' Hex ')
    • 2) Count

Function: Get the number

User_tuple = (' Hex ', ' Eric ', ' Seven ', ' hex ') v = user_tuple.count (' hex ') print (v)

#2
    • 3) Index

Function: Get the first index position worth

User_tuple = (' Hex ', ' Eric ', ' Seven ', ' hex ') v = user_tuple.index (' hex ') print (v) #0

    • 4) Note: Tuple last comma

Example

Li = (' HX ',) print (LI)

    • 5) cannot be modified by itself, but grandson can

User_tuple = (' Alex ', ' Eric ', ' Seven ', [' 1 ', ' 2 ', ' 3 '], ' A4 ')
# User_tuple[0] = 123 execution Error
# User_tuple[3] = [11,22,33] Execution error
USER_TUPLE[3][1] = ' 0 '
Print (User_tuple)

7.dict

Variable type

    • Create
v = {' name ': ' al ', ' Password ': ' 123123 '}

    • 1) Clear

Function: Empty

DiC = {' K1 ': ' v1 ', ' K2 ': ' V2 '}dic.clear () print (DIC)

    • 2) Copy

function: Shallow copy

DiC = {' K1 ': ' v1 ', ' K2 ': ' v2 '}v = dic.copy () print (v)

    • 3) Get

Function: Gets the specified value according to key, no error is present

DiC = {' K1 ': ' v1 ', ' K2 ': ' v2 '}v = dic.get (' k1111 ', 1111) print (v)

    • 4) Pop

Function: Delete and get the corresponding value values

# dic = {' K1 ': ' v1 ', ' K2 ': ' v2 '}# v = dic.pop (' k1 ') # print (DIC) # print (v)

Output:

{' K2 ': ' V2 '}v1

    • 5) Popitem

function: Random Delete key value pair, and get to delete key value

DiC = {' K1 ': ' v1 ', ' K2 ': ' v2 '}v = Dic.popitem () print (DIC) print (v)

Output:

{' K1 ': ' v1 '} (' K2 ', ' v2 ')

DiC = {' K1 ': ' v1 ', ' K2 ': ' v2 '}k,v = Dic.popitem () # (' K2 ', ' V2 ') print (DIC) print (K,V)

Output:

{' K2 ': ' V2 '}K1 v1

DiC = {' K1 ': ' v1 ', ' K2 ': ' v2 '}v = Dic.popitem () # (' K2 ', ' V2 ') print (DIC) print (v[0],v[1])

Output:

{' K1 ': ' v1 '}K2 v2

    • 6) SetDefault

Function: Add, delete if not present

DiC = {' K1 ': ' v1 ', ' K2 ': ' V2 '}dic.setdefault (' K3 ', ' v3 ') print (DIC) dic.setdefault (' K1 ', ' 1111111 ') print (DIC)

Output:

{' K2 ': ' v2 ', ' K1 ': ' v1 ', ' K3 ': ' V3 '} {' K2 ': ' v2 ', ' K1 ': ' v1 ', ' K3 ': ' V3 '}

    • 7) Update

Features: Batch additions or modifications

DiC = {' K1 ': ' v1 ', ' K2 ': ' V2 '}dic.update ({' K3 ': ' V3 ', ' K1 ': ' V24 '}) print (DIC)

Output:

{' K1 ': ' v24 ', ' K2 ': ' v2 ', ' K3 ': ' V3 '}

    • 8) Fromkeys

Function: Creates a new dictionary from the sequence key and value set to value.

Example:

DIC = Dict.fromkeys ([' K1 ', ' K2 ', ' K3 '],123) dic[' k1 '] = ' asdfjasldkf ' Print (DIC)

Output:

{' K2 ': 123, ' K1 ': ' asdfjasldkf ', ' K3 ': 123}

8.set

collection, non-repeating list, mutable type.

    • 1) Create
S1 = {"Alex", ' Eric ', ' Tony '}print (Type (S1)) print (S1)

Output:

<class ' Set ' >{' Alex ', ' Eric ', ' Tony '}

    • 2) Difference

Function: Presence in output S1, value not present in S2

S1 = {"Alex", ' Eric ', ' Tony ', ' II '}S2 = {"Alex", ' Eric ', ' Tony ', ' hexin '}v = s1.difference (s2) print (v)

Output:

{' II '}

    • 3) Difference_update

Function: exists in S1, S2 does not exist, then S1 is emptied and then re-assigned

S1 = {"Alex", ' Eric ', ' Tony ', ' II '}S2 = {"Alex", ' Eric ', ' Tony ', ' Hexin '}s1.difference_update (S2) print (S1)

Output:

{' II '}

    • 4) Symmetric_difference

Function: exists in S1, value not present in S2 and S2, value not present in S1

S1 = {"Alex", ' Eric ', ' Tony ', ' II '}S2 = {"Alex", ' Eric ', ' Tony ', ' hexin '}v = s1.symmetric_difference (s2) print (v)
{' II ', ' hexin '}

    • 5) Intersection

Function: Intersection

S1 = {"Alex", ' Eric ', ' Tony ', ' II '}S2 = {"Alex", ' Eric ', ' Tony ', ' hexin '}v = s1.intersection (s2) print (v)

Output:

{' Eric ', ' Alex ', ' Tony '}

    • 6) Union

Features: and set

S1 = {"Alex", ' Eric ', ' Tony ', ' II '}S2 = {"Alex", ' Eric ', ' Tony ', ' hexin '}v = s1.union (s2) print (v)

Output:

{' Alex ', ' Hexin ', ' Eric ', ' II ', ' Tony '}

    • 7) Discard

Function: Remove

S1 = {"Alex", ' Eric ', ' Tony ', ' II '}S2 = {"Alex", ' Eric ', ' Tony ', ' Hexin '}s1.discard (' Alex ') print (S1)

Output:

{' Eric ', ' Tony ', ' II '}

    • 8) Update

Features: Adding

S1 = {"Alex", ' Eric ', ' Tony ', ' Li Quan ', ' Li Quan '}s1.update ({' Alex ', ' 123123 ', ' FFF '}) print (S1)

Output:

{' FFF ', ' Li Quan ', ' 123123 ', ' Tony ', ' Alex ', ' Eric ', ' Li Quan 11 '}

9. Boolean Values
    • Create
A = Trueb = Flase
    • Transformation
The number conversion only 0 is flase, the string only "" is Flasev = bool () print (v) Two, the basic operation 1. Arithmetic operations:

"Python3 basic data type, basic 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.