Lipsky

Character string and Data type

字数统计: 340阅读时长: 2 min
2018/08/11 Share

Character String e.g.:#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> str1 = 'abcdefg'
>>> str1[2]
'c'
>>> str1[1]
'b'
>>> str1[-0] #the first one
'a'
>>> str1[-1] #the last one
'g'
>>> str1[1:4] #from the second to the fifth, but not contain the fifth
'bcd'
>>> str1[2:4] #from the third to the fifth, but also not contain the fifth
'cd'
>>> str1[0:-2]
'abcde'
>>> str1[:-2] #same to str1[0:-2]
'abcde'

Data type of Python#

  • create and operate list

demo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
>>> list1 = []			#define a list
>>> list1.append(1) #add an element to list
>>> list1.count(2) #calculate the occurrence number of 2 in the list
0
>>> list1.extend([2,3,5,4]) #add another list to list
>>> list1
[1,2,3,5,4]
>>> list1.index(5) #get the location of the element in list
3
>>> list1.insert(2,6)#insert 6 to the third location in list
>>> list1
[1,2,6,3,5,4]
>>> list1.pop(2) #delete the third element in list
6
>>> list1
[1,2,3,5,4]
>>> list1.remove(5) #remove 5 from the list
>>> list1
[1,2,3,4]
>>> list1.reverse() #reverse the element in list
>>> list1
[4,3,2,1]
>>> list1.sort() #rearrange the element in list
>>> list1
[1,2,3,4]
  • create and operate the tuple

Once defined, can’t be changed.

demo:

1
2
3
4
5
6
7
8
>>> tuple1 = ('a','b','c')	#define a tuple
>>> list1.insert(4,tuple1) #insert tuple1 to list
>>> list1
[1,2,3,4,('a','b','c')]
>>> tuple1[2] #get the third element in tuple
'c'
>>> tuple1[1:-1]
('b',)
CATALOG
  1. 1. Character String e.g.:#
  2. 2. Data type of Python#