This article describes the features and use of strings, lists, tuples, dictionaries, and sets in Python

String (STR)

Definition of a string

Strings can be defined using single quotes ‘, double quotes “, triple single quotes “, triple double quotes “””, as shown below

' ' '
"" "

Concatenation of strings

String concatenation in Python can be implemented using the + sign

+
str()
repr()

Escape character

Escape characters are not unique to Python. Python, like other languages, can use escape characters to represent special characters. The following table lists some commonly used escape characters

Escape character describe
\(at the end of the line) Line continuation operator
\ \ Backslash notation
Single quotes
Double quotation marks
\a Ring the bell
\b Backspace (Backspace)
\ 000 empty
\n A newline
\v Vertical TAB character
\t Horizontal tabs
\r enter
\f Change the page
\oyy Octal numbers, yy for characters such as: \o12 for newline
\xyy A hexadecimal number, yy represents a character, for example, \x0a represents a newline
\other Other characters are printed in normal format

Index and slice

A string is an ordered value consisting of one or more characters, as shown in the figure below. 0 is the index of the string p, and the index of the letter I is 7. The index can be from left to again, starting at 0, or from right to left, starting at -1

>>> s6='python is good'
>>> s6[1]
'y'
>>> s6.index('i')
7
Copy the code

If part of a string needs to be cut, the cut can be called slicing

>>> s6[2:11]
'thon is g'
>>> s6[2:]
'thon is good'
>>> s6[:7]
'python '
>>> s6[:99]
'python is good'
>>> s6[- 8 -:4 -]
' is '
>>> s6[- 8 -:]
' is good'
>>> s6[:4 -]
'python is '
>>> s6[1:11:2]
'yhni '
Copy the code
  • s6[2:11]Indicates that the string s6 is a character whose index value is 2-10
  • s6[2:]Represents the character after the index value is 2
  • s6[:7]Represents the character before the index value is 7
  • s6[:99]When the index value exceeds, all characters are fetched, but this is not recommended
  • s6[-8:-4]It’s going from right to left, between -8 and -4 to the character actuallys6[-8:-4]=s6[len(s6)-8:len(s6)-4]=s6[14-8:14-4]=s6[6:10]
  • s6[-8:]Represents all characters from right to left with an index value of -8
  • s6[:-4]All characters are indexed from right to left until the value of -4
  • s6[1:11:2]The value is a character whose index value is between 1 and 10, and the step size is 2

List (list)

Definition of a list

In Python, lists are defined using square brackets []. In contrast to other languages, Python does not specify that the elements in a list must be of the same type. The contents of a list can be strings, numbers, or even a list, tuple, dictionary, or collection

>>> l1=[]
>>> l1.append(1)
>>> l1.append("str")
>>> l1.append(["list1","list2"])
>>> l1.append(("123",123))
>>> l1.append({"456":456})
>>> l1.append(set('test'))
>>> l1
[1, 'str', ['list1', 'list2'], ('123', 123), {'456': 456}, {'s', 'e', 't'}]
>>> type(l1[0])
<class 'int'>
>>> type(l1[1])
<class 'str'>
>>> type(l1[2])
<class 'list'>
>>> type(l1[3])
<class 'tuple'>
>>> type(l1[4])
<class 'dict'>
>>> type(l1[5])
<class 'set'>
Copy the code

Index and slice

A list, like a string, has indexes and slices, but unlike a string, a list but index gets an item in a list

>>> l1[0]
1
>>> l1[1]
'str'
>>> l1[2:4]
[['list1'.'list2'], ('123'.123)]
>>> l1[:4]
[1.'str'['list1'.'list2'], ('123'.123)]
>>> l1[2[[:]'list1'.'list2'], ('123'.123), {'456': 456}, {'s'.'e'.'t'}]
>>> l1[- 1:]
[{'s'.'e'.'t'}]
>>> l1[:- 1]
[1.'str'['list1'.'list2'], ('123'.123), {'456': 456}]
Copy the code

List operations

List inversion

List inversion is also common in real programming, and you can reverse a list in the following way: Reverse () reverses the contents of the list

>>> l1
[1.'str'['list1'.'list2'], ('123'.123), {'456': 456}, {'s'.'e'.'t'}]
>>> l1[::- 1]
[{'s'.'e'.'t'}, {'456': 456},'123'.123),'list1'.'list2'].'str'.1]
>>> list(reversed(l1))
[{'s'.'e'.'t'}, {'456': 456},'123'.123),'list1'.'list2'].'str'.1]
>>> l1
[1.'str'['list1'.'list2'], ('123'.123), {'456': 456}, {'s'.'e'.'t'}]
>>> l1.reverse()
>>> l1
[{'s'.'e'.'t'}, {'456': 456},'123'.123),'list1'.'list2'].'str'.1]
Copy the code

List length, Max, min, add, remove

In a list, len() gets the length of the list, Max () gets the maximum value of the list,min() gets the minimum value of the list, append() adds data to the list, insert() adds data to the list to the specified location, The remove() function removes an item, and pop() removes the last item, which repeats the list by *

>>> l2=[5.1.9.2.9.3.1.4.7.5.6.7.9]
>>> len(l2)
8
>>> max(l2)
9
>>> min(l2)
1
>>> l2.append("addItem")
>>> l2.remove("addItem")
>>> l2.insert(0.99)
>>> l2
[99.5.1.9.2.9.3.1.4.7.5.6.7.9]
>>> l2.pop()
9
>>> l2*2
[99.5.1.9.2.9.3.1.4.7.5.6.7.99.5.1.9.2.9.3.1.4.7.5.6.7]
Copy the code

List join

Lists can be joined by a + sign, and extend() can be used to add the contents of one list to another. As you can see, the + sign does not change the list to its value. Extend () does

>>> l2
[5.1.9.2.9.3.1.4.7.5.6.7]
>>> l3
['l3-1'.'l3-2']
>>> l2+l3
[5.1.9.2.9.3.1.4.7.5.6.7.'l3-1'.'l3-2']
>>> l2
[5.1.9.2.9.3.1.4.7.5.6.7]
>>> l3
['l3-1'.'l3-2']
>>> l2.extend(l3)
>>> l2
[5.1.9.2.9.3.1.4.7.5.6.7.'l3-1'.'l3-2']
Copy the code

tuples

In Python, tuples are similar to lists, but they are special. Lists can be added, modified, or deleted, but tuples are immutable and cannot be added or modified

Definition of a tuple

>>> t1=123,'abc',['aaa']
>>> type(t1)
<class 'tuple'>
>>> t2=(123,'abc',['aaa'])
>>> type(t2)
<class 'tuple'>
Copy the code

Index and slice

Because tuples are similar to lists and are ordered, tuples also have indexes and slices

>>> t3=(123.'abc'['aaa'] and {"asda"."test"},3.3)
>>> t3[0]
123
>>> t3[1:]
('abc'['aaa'] and {'test'.'asda'}, 3.3)
>>> t3[:- 3]
(123.'abc')
Copy the code

The dictionary

Dictionary definition

There are many ways to define a dictionary, some of which are listed below

  1. Build an empty dictionary and add data to it
>>> d1={}
>>> type(d1)
<class 'dict'>
>>> d1[1]=123
>>> d1['2']="456"
>>> d1["a"]=789
>>> d1
{1: 123, '2': '456', 'a': 789}
Copy the code
  1. Build non-empty dictionaries directly
>>> d2={"name":"username",'age':18,'list':["item1","item2"]}
>>> type(d2)
<class 'dict'>
>>> d2
{'name': 'username', 'age': 18, 'list': ['item1', 'item2']}
Copy the code
  1. Use tuples to build dictionaries
>>> t3=(["key1","value1"],["key2","value2"])
>>> d3=dict(t3)
>>> d3
{'key1': 'value1', 'key2': 'value2'}
>>> type(d3)
<class 'dict'>
Copy the code
  1. Build directly using key=value
>>> d4=dict(id='1',age=1,name='test')
>>> type(d4)
<class 'dict'>
>>> d4
{'id': '1', 'age': 1, 'name': 'test'}
Copy the code

Dictionary operations

  • d[key]If the key does not exist, an error is reported
  • d[key]=valueValue is paid to the dictionary corresponding key
  • len(d)Returns the number of key-value pairs in the dictionary
  • key in dCheck if the dictionary contains values with a key
  • del d[key]Delete the image from the dictionary containing the key
  • d.get(key,defaultvalue)If the key does not exist, return None if defaultValue is not passed, otherwise return DefaultValue
  • d.setdefault(key,defaultvalue)If the corresponding key does not exist in the dictionary, add the corresponding key. If defaultValue is not specified, value is None; otherwise, defaultValue is specified
  • d.clear()Empty the contents of the dictionary
  • pop(key)andpopitem()For pop, a key is passed in, and for popItem, a random key-value pair is deleted
>>> d4['id']
'1'
>>> d4['id'] =2
>>> len(d4)
3
>>> 'id' in d4
True
>>> d4
{'id': 2.'age': 1.'name': 'test'}
>>> del d4['id']
>>> d4
{'age': 1.'name': 'test'}
>>> d4.get('age')
1
>>> d4.get('id')
>>> d4.get('id'.'1')
'1'
>>> d4
{'age': 1.'name': 'test'}
>>> d4.setdefault('id')
>>> d4
{'age': 1.'name': 'test'.'id': None}
>>> d4.setdefault('id1'.1)
1
>>> d4
{'age': 1.'name': 'test'.'id': None.'id1': 1}
>>> d4.clear()
>>> d4
{}
>>> d5={'id': 2.'age': 1.'name': 'test'.1:999.2:Awesome!.3:777}
>>> d5.pop('id')
2
>>> d5
{'age': 1.'name': 'test'.1: 999.2: Awesome!.3: 777}
>>> d5.popitem()
(3.777)
>>> d5
{'age': 1.'name': 'test'.1: 999.2: Awesome!}
Copy the code

The copy of the dictionary

Dictionaries can be copied using the copy() method, and making changes to one of these pairs does not affect the original dictionary

>>> d6={1:1.2:2.2.'3':'3'.'l': [123.'123'.'456']}
>>> d6
{1: 1.2: 2.2.'3': '3'.'l': [123.'123'.'456']}
>>> d7=d6.copy()
>>> d7
{1: 1.2: 2.2.'3': '3'.'l': [123.'123'.'456']}
>>> d7[1] ='999'
>>> d7
{1: '999'.2: 2.2.'3': '3'.'l': [123.'123'.'456']}
>>> d6
{1: 1.2: 2.2.'3': '3'.'l': [123.'123'.'456']}
Copy the code

However, if you change the list, the contents of both dictionaries are changed together, because the copy is only a shallow copy, and the address of the list in both dictionaries is the same

>>> d7['l'].append(74125)
>>> d7
{1: '999'.2: 2.2.'3': '3'.'l': [123.'123'.'456'.74125]}
>>> d6
{1: 1.2: 2.2.'3': '3'.'l': [123.'123'.'456'.74125]}
>>> id(d6['l'])
4540976712
>>> id(d7['l'])
4540976712
Copy the code

To implement deepcopy, you need to import the copy module and use the deepcopy() function for deepcopy

>>> d7
{1: '999'.2: 2.2.'3': '3'.'l': [123.'123'.'456'.74125]}
>>> import copy
>>> d8=copy.deepcopy(d7)
>>> d8
{1: '999'.2: 2.2.'3': '3'.'l': [123.'123'.'456'.74125]}
>>> d8['l'].append('append')
>>> d8
{1: '999'.2: 2.2.'3': '3'.'l': [123.'123'.'456'.74125.'append']}
>>> d7
{1: '999'.2: 2.2.'3': '3'.'l': [123.'123'.'456'.74125]}
Copy the code

A collection of

Definition of set

The following is how a collection is defined. The collection automatically removes duplicate data and the elements in the collection are not needed

>>> s1=set('fglsdfglsfghalerwer')
>>> s1
{'a'.'r'.'d'.'h'.'w'.'s'.'e'.'g'.'f'.'l'}
>>> s2=set([1.2.58.1.5.6.7.8.6.9])
>>> s2
{1.2.5.6.7.8.9.58}
Copy the code

Operation of set

  • The set can be accessed throughadd()Implements the addition of a collection
  • throughupdate()You can add data from one set to another set
  • pop()You can randomly delete an element from the collection
  • remove()The specified element in the collection can be deleted, or an error is reported if the element does not exist
  • discard()You can delete specified elements from the collection, or return None if None exists
  • clear()You can empty all elements of the collection
>>> s2.add('test')
>>> s2
{1.2.5.6.7.8.9.'test'.58}
>>> s1
{'a'.'r'.'d'.'h'.'w'.'s'.'e'.'g'.'f'.'l'}
>>> s1.update(s2)
>>> s1
{1.2.5.6.7.'h'.8.9.'test'.'e'.'d'.'a'.'r'.'w'.'s'.'g'.'f'.58.'l'}
>>> s2
{1.2.5.6.7.8.9.'test'.58}
>>> s1.pop()
1
>>> s1.remove('test')
>>> s1
{2.5.6.7.'h'.8.9.'e'.'a'.'w'.'s'.'g'.58.'d'.'r'.'f'.'l'}
>>> s1.discard('r')
>>> s1
{2.5.6.7.'h'.8.9.'e'.'a'.'w'.'s'.'g'.58.'d'.'f'.'l'}
>>> s1.clear()
>>> s1
set()
Copy the code