Python string, list, tuple

Source: Internet
Author: User

Common Methods for strings:

Name.count ('h'counts the number of occurrences of h in name Name.find ('h') Find the index of H'?'. Join (name) use Hello stitching name.encode ('gb2312'Convert the string to gb2312 encoded Name.decode ('gb2312'), which translates a gb2312 encoded string into a Unicode encoding Name.endswith ('. txt') Whether the string ends with an xx boolean type startswith ('A'the string is preceded by a Boolean name of XX: IsDigit () determines whether the numeric Boolean Name.strip () goes to the space Name.replac ('xx',"'in the string, XX replaces the Name.split (','The string is separated by a comma, and a listname.splitlines () is returned with a newline character that splits the string and returns a list

Common Ways to List

Increase:

msg = ' Woshi ' name = [' Yige ', ' xiaoshide ', ' Hundan ']name.append (msg) #从最后面开始插入name. Insert (1,msg) #从指定位置插入, this 1 represents subscript            

By deleting:

msg ='Woshi'name= ['Yige','Xiaoshide','Hundan']name.remove ('Yige')#deletes the specified valuedelNAME[0]#Delete the value at the specified locationName.pop ()#If you don't pass in the subscript, delete the last value, and pass in the subscript to delete the value at the specified position.Name.clear ()#Clear List

Change:

' Woshi '  = ['yige','xiaoshide','Hundan  ']name['baby'# Modify the value labeled 1

Check:

' Woshi '  = ['yige','xiaoshide','Hundan  ']print(name[0])# Gets the first element print(name[-1] )#-1 for the last element

Some common methods:

Print (Name.index ('yige')) # Fetch Index Print (Name.count ('yige')) # number of occurrences of CC name.clear ()# empty list print(Name.sort ())# sort name.extend (name2)# extension list, that is, add the value of name2 to name name.reverse ()# inverse Array, Will change the value of the original array

Other:

A = [1,2,3,4,5,6,7] for in range (len (a))     print(I,a[i]) The result is the same as the following for in   Enumerate (a     )print(item,p)

Slice:

Gu Tou regardless of the tail
The value in front of the slice colon, omitted, which represents the previous value.
The value after the slice colon, omitted from the word, represents the value of all subsequent values
Just write a colon, take the entire list, it can be used to copy a new list
Step default does not write, is 1, write on the step, write a few elements to take once
When the step is negative, the value starts at the end of the list and is a positive number, starting at the beginning of the list.
The operation of the slice subscript also applies to the string

Nums = [1,2,3,4,5,6,7,8,9,10]nums[1:4]#Remove the value from Mark 1 to subscript 4, including 1, excluding 4NUMS[1:-1]#Remove the value labeled 1 to-1, excluding -1Nums[0:3]#remove the value from 0 to 3, excluding 3Nums[:3]#remove the value from 0 to 3, excluding 3, as in the above effect, 0 can omit not to writeNums[2:]#take all elements that begin with the second subscript#The following steps are addedNUMS[::2]#This delegate takes all the elements and then takes one every 2 elements>>> 1 3 5 7 9#results of the outputNums[1:8:3]#The delegate takes the second element, starts at the end of the eighth, and takes it 3 times.>>>[2,5]#Output Results

Meta-group:

Tuples are actually the same as lists, not the same, the value of the tuple can not change, once created, it can no longer change, for example, to save the database connection information, the connection information in the program is not to be changed, if the database is not connected to the program on the end of the Duzi, so that you can use the tuple, tuple it , also prompted others, see is a tuple words, it means that this value can not be changed, the definition of the tuple is used (), parentheses, tuple only two methods, that is, Count and index

Mysql_coon = ('192.168.1.109','root','123456  ', 3306,'my_db')# define Tuples

Mysql_config.count (3306) #查询出现的次数
Mysql_config.index (' root ') #获取指定元素的下标

Dictionary:

Features of the dictionary:

The dictionary is unordered because it has no subscript and is indexed with key, so it is unordered

The key of the dictionary must be unique because it is indexed by key, so key cannot be duplicated and is inherently heavy.

Increase:

Infos = {'Marry': [18,18612512981,'Beijing'],'Amy': [20,18612512991,'Shandong'],'Lily': [25,18612532981,'Henan']}infos['Andy']=[22,18712512981,'Hebei']#Increase

Modify:

Infos = {'Marry': [18,18612512981,'Beijing'],'Amy': [20,18612512991,'Shandong'],'Lily': [25,18612532981,'Henan']}infos['Marry': [38,18612512981,'Beijing']]

Delete:

Infos = {'Marry': [18,18612512981,'Beijing'],'Amy': [20,18612512991,'Shandong'],'Lily': [25,18612532981,'Henan']} infos.pop ('Marry')#standard method of deletion delinfos['Marry']#use the Del method to deleteInfo.popitem ()#randomly delete a value

Inquire:

Infos = {'Marry': [18,18612512981,'Beijing'],'Amy': [20,18612512991,'Shandong'],'Lily': [25,18612532981,'Henan']} infos.get ('Maryy')#Gets the marry information, which returns none if key does not existinfos['Marry']#Get marry information, this way if key does not exist, it will be an error
'Marry' inchInfos#determine if marry is in this dictionary, returns TRUE or false

Built-in methods for dictionaries:

DIC = {'STU1':'cc','STU2':'Andashu','STU3':'Niuniu'} Print(Dic.values ())#Print all value Print(Dic.keys ())#Print all the keys Print(Dic.setdefault ('STU1','Fengluo'))#If this key exists, then do not move it, do not exist, add aDic2 = {'STU1':'Sriba','Stu10':'Baidu'} dic.update (Dic2)#update the dictionary value, if the key exists, it is updated, does not exist to add Print(Dic.items ())#The dictionary is converted into a list 

 







Python string, list, tuple

Related Article

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.