1- tuple basis / list / string / dictionary / sets / document / string encoding transformation

A: List:

names=["4ZhangYang","Guyun","xXiangPeng",["alex","jack"],"ChenRonghua","XuLiangchen"]

print (names [1: 3]) # Hand care regardless of the end sections, the second extraction / three

print (names [3]) # fourth sections taken

print (names [-2:]) # last two sections taken

   

#increase:

names.append ( "LeiHaidong") # Finally join

names.insert (1, "ChenRonghua") # into the front guyun

   

#delete delete three ways

names.remove("ChenRonghua")

del names[1]=names.pop(1)

names.pop(1)

   

#modify

names [2] = "Peng to" Modify #

 

print (names.count ( "ChenRonghua")) # calculate the number of chenronghua appear

names.clear () # Empty

names.reverse () # reverse reverse

names.sort () # sorted alphabetically

print(names)

names2=[1,2,3,4]

names

names.extend (names2) # merge tuple

the names2

print(names,names2)

   

Three printing methods:

print(names[0:-1:2])

print (names [:: 2]) # 0 can be omitted

print(names[:])

   

   

Two: tuple:

And the list is basically the same, almost:

1 . Not CRUD

2 . Small brackets in place of brackets

3 . But you can use statistics and view: count and index

   

Added: Remove the list subscript

   

   

   

   

Three: String

Can not be modified.

name = "my \tname is {name} and i am {year} old"

Common applications of string functions:

print (name.capitalize ()) # capitalized

The number of print (name.count ( "a")) # statistics appear

print (name.center (50, "-")) # 50 spaces, insufficient - padded

print (name.endswith ( "ex")) # what end

print (name.expandtabs (tabsize = 30)) # \ t turn into 30 spaces

print (name [name.find ( "name"):]) #find ( "name") returns 4, the string may be sliced

print (name.format (name = 'alex', year = 23)) # Format

print(name.format_map( {'name':'alex','year':12} )) #字典

print ( 'ab23'.isalnum ()) # determines whether or Arabic numerals

print ( 'abA'.isalpha ()) # if it is pure English characters

print ( '1A'.isdecimal ()) # is a decimal

print ( '1A'.isdigit ()) # whether the integer

print ( 'a 1A'.isidentifier ()) # interpretation is not a valid identifier

print ( '33A'.isnumeric ()) # whether a number

print ( 'My Name Is' .istitle ()) # whether the title, capitalize the first letter of each

print ( 'My Name Is' .isprintable ()) #tty file, drive file is unprintable

print ( 'My Name Is' .isupper ()) # is not capitalized

print (. '+' join ([ '1', '2', '3'])) # 2 + 3 + 1 represents; often

print (name.ljust (50, '*')) # 50 long, make up the shortage with *, up in the final (Last)

print (name.rjust (50, '-')) # 50 length, with less than - fill

print ( 'Alex'.lower ()) # all lowercase

print( 'Alex'.upper() )

print ( '\ nAlex'.lstrip ()) # to the left of the spaces and line breaks

print( 'Alex\n'.rstrip() )

print( ' Alex\n'.strip() )

   

p = str.maketrans ( "abcdefli", '123 $ @ 456') # Alternatively, for example into a 1, may be used as the password

print("alex li".translate(p) )

   

print ( 'alex li'.replace (' l ',' L ', 1)) # l is the replacement of an L

print ( 'alex lil'.rfind (' l ')) # 5 return, from the left to find the maximum number of index

print ( '1 + 2 + 3 + 4'.split (' + ')) # segmentation according to what

print('1+2\n+3+4'.splitlines())

print ( 'Alex Li'.swapcase ()) # sensitive conversion

print ( 'lex li'.title ()) # capitalized

print ( 'lex li'.zfill (50)) # fill bits

   

   

Four: Dictionary

Note: Key Try not to write Chinese:

info = {

'stu1101': "TengLan Wu",

'Stu1102': "LongZe Luola",

'stu1103': "XiaoZe Maliya",

}

   

check:

info [ 'stu1104'] # being given absent

print (info.get ( 'stu1103')) # does not exist will return null

   

modify:

info["stu1101"] ="武藤兰"

   

increase:

info["stu1104"] ="CangJing"

   

delete:

#of the

#del info["stu1101"]

   

info.pop("stu1101")

info.popitem () # delete a random

   

   

Update:

b ={

'stu1101': "Alex",

1:3,

2:5

}

   

info.update (b) # merge two dictionaries, and set to take

print (info.items ()) # convert into a dictionary list

   

Two kinds of dictionaries cycle:

for i in info:

print(i,info[i])

   

for k,v in info.items():

print (k, v)

Difference: the first is more efficient, to become the second first list of conversion.

   

   

Multi-level nested dictionaries and operations

   

av_catalog = {

"Europe": {

" Www.youporn.com ": [ "a lot of free, the world's largest", "quality in general"],

" Www.pornhub.com ": [ "a lot of free, are also high," "high quality than yourporn"],

"Letmedothistoyou.com": [ "mostly selfie, a lot of high-quality images," "limited resources, updating slow"],

"X-art.com": [ "the quality is very high, really high," "all the charges, please bypass ratio Cock"]

},

"Japan and South Korea": ​​{

"Tokyo-hot": [ "What quality do not know, personally do not like Japan and South Korea have been the norm," "I heard a fee."]

},

"mainland":{

"1024": [ "all free, good, good life of peace", "server in a foreign country, slow"]

}

}

   

#modify:

av_catalog [ "continent"] [ "1024"] [1] = "can make a mirror at home."

av_catalog.setdefault ( "Continental", { "www.baidu.com": [1,2]}) # can take to, return, take less, to reset

   

   

Three-level menu examples:

   

   

   

   

Five: collection

   

Is a set of unordered not repeated combinations of data, his role is as follows:

Deduplication:

list_1 = [1,4,5,7,3,6,7,9]

list_1 = set(list_1)

   

list_2 =set([2,6,0,66,22,8,4])

print(list_1,list_2)

   

# Intersection

print( list_1.intersection(list_2) )

   

# Union

print(list_1.union(list_2))

   

#差集 in list_1 but not in list_2

print (list_1.difference (list_2)) # Save common binding portion 1

   

# Child Collection

list_3 = set([1,3,7])

print subset (list_3.issubset (list_1)) # 3 is 1 of

print superset (list_1.issuperset (list_3)) # 1 whether or 3

   

# Symmetric difference

print (list_1.symmetric_difference (list_2)) # union minus the intersection

   

list_4 = set([5,6,7,8])

print (list_3.isdisjoint (list_4)) # Return True if two sets have a null intersection. there was no communication (false)

   

   

# Intersection

print(list_1 & list_2)

   

# Union

print(list_2 | list_1)

   

# Difference set

print(list_1 - list_2) # in list 1 but not in list 2

   

# Symmetric difference

print(list_1 ^ list_2)

   

list_1.add (999) # increased

list_1.update ([888,777,555]) # Review

list_1.remove (999) # delete one, there will be an error

print (list_1.discard (888)) # specify a value, if there is deleted, if there is no operation

print (list_1.pop ()) # delete any of

   

   

六:文件
#data = open("yesterday",encoding="utf-8").read()

f = open ( "yesterday2", 'a', encoding = "utf-8") # filehandle

#a = append additional

f.write("\nwhen i was young i listen to the radio\n")

data = f.read()

print('--read',data)

f.close()

 

print (f.encoding) # print type, as herein utf-8

print(dir(f.buffer) ) #

   

Open = F ( "yesterday2", 'R & lt', encoding = "UTF-. 8") # filehandle

#high bige

   

count = 0

for line in f:

if count == 9:

print ( '---- I am dividing line ----------')

count += 1

continue

print(line)

count +=1

   

#low loop

   

for index,line in enumerate(f.readlines()):

if index == 9:

print ( '---- I am dividing line ----------')

continue

print(line.strip())

#for i in range(5):

# print(f.readline())

'''

   

   

Open = F ( "yesterday2", 'R & lt', encoding = "UTF-. 8") # filehandle

print (f.tell ()) # letter Location

print (f.readline (20)) # How many characters take

print(f.tell())

f.seek (9) # from a few start

print('2------',f.readline())

   

print (f.writable ()) # is writable

   

f.flush () # to force a refresh to the hard disk, not a full refresh

Example 1: promptly flushed out

   

   

Example 2: Production of the progress bar;

Import sys,time

For I in range(20):

sys.stdout.write("#")

sys.stdout.flush()

time.sleep(0.1)

   

   

   

   

   

Open = F ( "yesterday2", 'A', encoding = "UTF-. 8") # filehandle

f.seek (10) # from a few start

f.truncate (20) # 20 cutoff to retain, remove the back

   

   

   

f = open ( "yesterday2", 'r +', encoding = "utf-8") # write, open, continue to write the content. Most used

f = open ( "yesterday2", 'w +', encoding = "utf-8") # read-write file handle, no far-reaching

f = open ( "yesterday2", 'a +', encoding = "utf-8") # additional write file handle

f = open ( "yesterday2", 'rb') # binary read for network transmission

f = open("yesterday2",'wb') #二进制写,不能读

f.write("hello binary\n".encode())

f.close()

备注:Open : r w a r+ w+ a+ rb wb ab

   

#实例:将yesterday2拷贝到新建的yesterday2bak中,并修改部分

import sys

f = open("yesterday2","r",encoding="utf-8")

f_new = open("yesterday2bak","w",encoding="utf-8")

   

for line in f:

if "我的双眼却视而不见" in line:

line=line.replace("我的双眼却视而不见","wangbao的双眼却视而不见")

f_new.write(line)

f.close()

f_new.close()

   

   

   

实例:打开多个文件,且不用关心文件关闭问题,这种自动关闭

import sys

#可以打开多个文件

with open("yesterday2","r",encoding="utf-8") as f ,\

open("yesterday2", "r", encoding="utf-8") as f2:

for line in f:

print(line)

   

   

   

七:字符串编码转换

   

7.1 在python2中:默认utf-8

   

Utf-8转成Unicode,再转成GBK

   

GBK转UTF-8也要先转成Unicode

   

   

7.2 在python3中:默认unicode(都是两个字节)

#-*-coding:gbk-*- #文件中申明为gbk

   

import sys

print(sys.getdefaultencoding())

__author__ = "Alex Li"

   

s = "你哈" #本python中还是使用Unicode

print(s.encode("gbk"))

print(s.encode("utf-8"))

print(s.encode("utf-8").decode("utf-8").encode("gb2312").decode("gb2312"))

   

   

   

   

   

Guess you like

Origin www.cnblogs.com/yifanrensheng/p/11351246.html