Python 3: Data Type
-. String
A string is a sequence of characters.
A string literal uses quotes, 如'hello' or "hello"
For strings, + means "concatenate"
When a string contains numbers, it is still a string.
We can convert numbers in a string into a number using int()
We prefer to read data in using strings and then parse and convert the data as we need(input中输入的所有值,包括数字,type为string,如需与数字进行计算,需先转换为int或float)
This gives us more control over error situations and/or bad user input
(Raw) input numbers must be converted from strings
We can get at any single character in a string using an index specified in square brackets. The index value must be an integer and starts at zero, and the index value can be an expression that is computed. 如:
fruit = 'banana'
letter = fruit [1]
print (letter) 显示a
又如:x = 3
w = fruit [x - 1]
print (w) 显示n
You will get a python error if you attempt to index beyond the end of a string, so be careful when constructing index values and slices. (index不能超出string或list的字节长度)
There is a built-in function len() (可以用在string或list或dictionary下)that gives us the length of a string. The function is some stored code that we use and takes some input and produces an output. 如:
fruit = 'banana'
print (len (fruit)) 显示6
1. Looping Through Strings
Using a while statement and an iteration variable, and the len function, we can construct a loop to look at each of the letters in a string individually. 如:
fruit = 'banana'
index = 0
while index < len (fruit) :
letter = fruit [index]
print (index, letter) (显示index是什么,所对应的letter是什么)
index += 1 (在while loop中必须要在循环结束前,即print之后,添加一个让loop往前走的指令,跳出loop,否则loop会无限死循环)
显示 0 b; 1 a; 2 n; 3 a; 4 n; 5 a
A definite loop using a for statement is much more elegant. The iteration variable is completely taken care of by the for loop. 如:fruit = 'banana'
for letter in fruit :
print (letter)
2. Slicing Strings
We can also look at any continuous section of a string using a colon operator(:). The second number is one beyond the end of the slice- up to but not including. If the second number is beyond the end of the string, it stops at the end. 如:
s= 'Monty Python'(字符数量从左至右,从0开始数,空格算一个字符)s [:] (:左右都不填数字,默认显示所有字符)
print (s [0:4]) 显示 Mont(注意【】 左边的数字是包含本身字符在内的,右边的数字不包含本身字符在内,即本身第几个字符-1,【0:4】即第0个字符至第3个字符)
print (s [6:7]) 显示 P
print (s [6:20]) 显示 Python(如果:右边的数字超出了最后一个字符的顺序,或不填任何数值,则默认右边数字读取到最后一个字符,即从左边数字对应字符至结尾字符的全部字符)
If we leave off the first number or the last number of the slice, it is assumed to be the beginning or end of the string respectively. 如:s = 'Monty Python'
print (s [:2]) 显示 Mo
print (s [8:]) 显示 thon
print (s [:]) 显示 Monty Python
Note:string最后一个字母或数字字符所对应的数字顺序为-1. 如:
s = 'Monty Python python3'
print (s [-1]) 显示 3
print (s [:-1]). 显示 Monty Python python
print (s [::-1]) 显示 3onhtyp onhtyP ytnoM(即原所有字符倒写)
3. String Concatenation
When the + operator is applied to strings, it means "concatenation". 如:
a = 'Hello'
b = a + 'There'
print (b) 显示 HelloThere
c = a + '' + 'There' 显示 Hello There
第二种连接方式,如:
a = 'hello'
b = 'there'
c = '!'
a + '' + b + '' + c 可显示hello there !
也可 ‘’. join ([a, b, c]) 显示hello there !
4.Using in as a logical Operator
The in keyword can also be used to check to see if one string is "in" another string.
The in expression is a logical expression that returns True or False and can be used in an if statement. 如:
fruit = 'banana'
'n' in fruit 显示 True
'm' in fruit 显示 False
'nan' in fruit 显示 True
if 'a' in fruit
print ('Found it!') 显示 Found it!
5. String Library(可去python官网查看)
Python has a number of string functions which are in the string library. These functions are already built into every string- we invoke them by appending the function to the string variable. These functions do not modify the original string, instead they return a new string that has been altered.
lower() upper()
6. The replace() function is like a "search and replace" operation in a word processor. It replaces all occurrences of the search string with the replacement string. 如:
a = 'Hello Bob'
b = a. replace ('Bob', 'Jane')
print (b) 显示 Hello Jane(将Bob替换成了Jane)
b = a. replace ('o', 'x')
print (b) 显示 Hellx Bxb(将o替换成了x)
7. Stripping Whitespace
Sometimes we want to take a string and remove whitespace at the beginning and/or end. lstrip() and rstrip() remove whitespace at the left or right. strip() removes both beginning and ending whitespace. 如:
greet = ' Hello Bob '
greet. lstrip() 显示 ‘Hello Bob '
greet. rstrip() 显示 ‘ Hello Bob'
greet. strip() 显示 ‘Hello Bob’
8. Parsing and Extracting- using find() 如:string = 'From stephen. [email protected] Sat Jan 5 09:14:16 2008'
a = string. find ('@')
print (a) 显示 21
b = string. find (' ', a)(a之后的第一个‘’)显示31
c = string [a + 1 : b] 显示 uct. ac. za
二. List & tuple
A list is a kind of collection.
A collection allows us to put many values in a single "variable".
A collection is nice because we can carry all many values around in one convenient package.
1. List Constants
List constants are surrounded by square brackets and the elements in the list are separated by commas.
A list element can be any Python object - even another list.
A list can be empty.
2. Looking Inside Lists
Just like strings, we can get at any single element in a list using an index specified in square brackets.
注:list中以element为顺序,从0开始
3. Lists are Mutable
Strings are "immutable" - we cannot change the contents of a string - we must make a new string to make any change.
Lists are "mutable" - we can change an element of a list using the index operator.
注:在list中可直接替换element. 如:
list = [2, 14, 26, 41, 63]
list [2] = 28
print (list) 显示 [2, 14, 28, 41, 63]
4. How Long is a List
The len() function takes a list as a parameter and returns the number of elements in the list.
Actually len() tells us the number of elements of any set or sequence (such as a string......)
5. Using the range function
The range function returns a list of numbers that range from zero to one less than the parameter.
We can construct an index loop using for and an integer iterator.
A tale of two loops:
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print ('Happy New Year:', friend). or
for i in range (len (friends)) :
friend = friends [i]
print ('Happy New Year:', friend)
两种方法显示结果一样
6. Concatenating lists using "+"
We can create a new list by adding two existing lists together. 如:
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print (c) 显示 [1, 2, 3, 4, 5, 6]
注:如果list在相加时有重复的element,则不会去除相同element,即相加后的list会有重复值
7. Lists can be sliced using ":"
Remember: just like in strings, the second number is "up to but not including"
8. List Methods
(1) Building a List from Scratch (append是在空list里加element,pop是在有element的list里删element,pop后面要注明element的顺序数字index,如没数字,默认删最后一个element)
We can create an empty list and then add elements using the append method.
The list stays in order and new elements are added at the end of the list.
Pop function takes an element out of a list.
如:stuff = list ()
stuff. append ('book')
stuff. append (99)
print (stuff) 显示 ['book' , 99]
stuff. append ('cookie')
print (stuff) 显示 ['book',99,'cookie']
stuff. pop (0) 显示 ‘book’
print (stuff) 显示 [99, 'cookie']
(2) Is Something in a list ?
Python provides two operators that let you check if an item is in a list.
These are logical operators that return True of False. They do not modify the list. 如:
some = [1, 9, 21, 10,16]
9 in some 显示 True
15 in some. 显示 False
20 not in some 显示 True
(3) A List is an Ordered Sequence
A list can hold many items and keeps those items in the order until we do something to change the order.
A list can be sorted (i.e., change its order).
The sort method (unlike in strings) means "sort yourself". 如:
friends = ['Joseph' , 'Glenn' , 'Sally']
friends. sort()
print (friends) 显示 ['Glenn', 'Joseph', 'Sally'](按照数字或string第一个字母,由小到大排序)
print (friends [1]) 显示 Joseph
(4) Built-in Functions and Lists
There are a number of functions built into Python that take lists as parameters.
Remember the loops we built ? These are much simpler. 如:
nums = [3, 41, 12, 9, 74, 15]
print (len (nums)) 显示 6
print (max (nums)) 显示74
print (min (nums)) 显示 3
print (sum (nums)) 显示 154
print (sum (nums) / len (nums)) 显示 25
(5) Best Friends: Strings and Lists
Split breaks a string into parts and produces a list of strings. We think of these as words. We can access a particular word or loop through all the words. 如:
abc = 'With three words'
stuff = abc. split()
print (stuff) 显示 ['With', 'three','words']
print (len (stuff)) 显示 3
print (stuff [0]) 显示 With
When you do not specify a delimiter, multiple spaces are treated like one delimiter.
You can specify what delimiter character to use in the splitting. 如:
line = 'A lot of spaces'
etc = line. split()
print (etc) 显示 ['A', 'lot', 'of', 'spaces']
line = 'first;second;third'
thing = line. split()
print (thing) 显示 ['first;second;third']
print (len (thing)) 显示 1
thing = line. split(';')
print (thing) 显示 ['first', 'second', 'third']
print (len (thing)) 显示 3
Sometimes we split a line one way, and then grab one of the pieces of the line and split that piece again.(Double Split Pattern)
9. Tuples are like lists- list 用[], tuple用()(tuples与lists的区别是tuple不能添,删,改,即不能变更,同时把list改成tuple时会把相同值duplicate elements进行删减)
Tuples are another kind of sequence that functions much like a list - they have elements which are indexed starting at 0.
Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string. (Tuples are "immutable")
Things not to do with tuples: 如:
sort() , append() , reverse() 等(list可以,tuple不行)
A tale of Two Sequences :
l = list ()
dir (l)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
t = tuple ()
dir (t)
['count', 'index']
10. Tuples are more efficient
Since Python does not have to build tuple structures to be modifiable, they are simpler and more efficient in terms of memory use and performance than lists. So in our program when we are making "temporary variables", we prefer tuples over lists.
11. Tuples and Assignment
We can also put a tuple on the left-hand side of an assignment statement. We can even omit the parentheses. 如:
(x, y) = (4, 'fred')
print (y) 显示 fred
(a, b) = (99, 98)
print (a) 显示 99
12. Tuples are Comparable
The comparison operators work with tuples and other sequences. If the first item is equal, Python goes on to the next element, and so on, until it finds elements that differ. 如:(0, 1, 2) < (5, 1, 2) True
(0, 1, 2000000) < (0, 3, 4) True
('Jones', 'Sally') < ('Jones', 'Sam') True
('Jones', 'Sally') > ('Adams', 'Sam') True