一 for 循环知识补充
range 范围
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
Notice that the ending number is not included.
We can omit the starting position and step parameters.
可以省略起始位置和步长,默认起始位置为0,步长为1
and the step could be negative 步长可以为负数
#range步长的用法
for i in range(1, 10, 2):
print(i)
#range步长为负
for i in range(20, 10, -2):
print(i)
enumerate 列举索引
Python's enumerate() lets you write Pythonic for loops when you need a count and the value from an iterable(可迭代的). The big advantage of enumerate() is that it returns a tuple(元组) with the counter and value, so you don't have to increment the counter yourself.
for hobby in enumerate(["chi", "he", "piao", "du"]): #基本用法
print(hobby)
#也可以在for后面跟2个变量
for num, hobby in enumerate(["chi", "he", "piao", "du"]):
print(num, hobby)
print(type(num)) #输出的第一个变量为整型
print(num+1, hobby)
二 可变类型与不可变类型
mutable object and immutable object
Every variable in python holds an instance of an object. There are two types of objects in python:mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime and it can’t be changed afterwards. However, it’s state can be changed if it is a mutable object.
To summarise the difference, mutable objects can change their state or contents and immutable objects can’t change their state or content.
Mutable type | Immutable type |
---|---|
list | int,float,complex |
dictionary | string |
tuple |
三 数字类型 numeric types
Variables of numeric types are created when you assign a value to them:
Numeric types usually used for arithmetic and comparison calculation
they are all immutable types
一般为不可变类型
定义 definition
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Float
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Complex
Complex numbers are written with a "j" as the imaginary part.
a = 5 + 3j
print(type(a))
print(a.real) # 打印复数实部
print(a.imag) # 打印复数虚部
转换 Convert
These types can be converted to each other
And we can turn "string" into "Int" and “float”
But the string here must consist of numbers
a = -2 # 整型转换为浮点型,注意后面要有.0
b = float(a)
print(b, type(b))
c = -1.987 # 浮点型转换为整型,注意是直接截取,不是四舍五入也不是取整
d = int(c)
print(d, type(d))
e = "1997" # 字符串转换为整型或浮点型
f = int(e)
g = float(e)
print(f, type(f), g, type(g))
四 字符串 Strings
定义 definition
Strings in python are surrounded by either single quotation marks, or double quotation marks.
在一对单引号或者双引号之间,或者三引号之间(用于多行内容)
Strings are immutable types
转换 Convert
All types can be converted to strings by command str()
五 字符串操作
转义符 Escape Characters ""
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by double quotes:
We can also put r in front of the string to achieve that when there is an escape character in the string
txt = "We are the so-called "Vikings" from the north."
txt = "We are the so-called 'Vikings' from the north."
print(r"a/b/c")
字符串可以使用索引 Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Square brackets(中括号) can be used to access elements of the string.
my_name="matthews"
print(my_name[4]) #注意,索引从0开始数
循环取用字符串 Looping through a string
Since strings are arrays, we can loop through the characters in a string, with a for
loop.
my_name="matthews"
for i in my_name:
print(i)
切片 Slicing
You can return a range of characters by using the slice syntax(句法).
Specify(指定) the start index and the end index, separated by a colon(冒号), to return a part of the string.
my_name = "matthews"
print(my_name[2:5]) # 注意,不包括终止值
print(my_name[1:4:2]) # 使用步数
print(my_name[4:1:-1]) # 注意,使用步数完成倒序,方法,颠倒前后两数,并全部-1
print(my_name[:]) # 注意,相当于复制操作
成员运算 in/ not in
To check if a certain phrase or character is present in a string, we can use the keyword in:
my_name = "matthews"
if "at" in my_name:
print ("Yes,'at' is present")
移除前后空格 Strip (Remove whitespace)
Whitespace is the space before and/or after the actual text, and very often you want to remove this space.
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
替换 Replace String
The replace() method replaces a string with another string:
my_name = "matthews t"
print(my_name.replace("t","b")) #把所有的t替换为b
print(my_name.replace("tt","b")) #把所有的tt替换为b
切分 Split String
The split() method returns a list where the text between the specified separator becomes the list items.
ip_address="192.168.1.1"
print(ip_address.split("."))
字符串中的引用 Format String
We cannot combine strings and numbers directly
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:
基本用法
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
按顺序引用
The format() method takes unlimited number of arguments, and are placed into the respective placeholders
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
按索引引用
You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
六 字符串完整内建函数
https://www.runoob.com/python3/python3-string.html
七 列表
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
定义 Definition
Lists are created using square brackets:
列表元素特点 List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
有序的 Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
可变的 Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
允许重复 Allow Duplicates
Since lists are indexed, lists can have items with the same value:
更改列表元素 Change list items
取列表元素 Access List Items
List items are indexed and you can access them by referring to the index number:
更改列表元素 Change List Items
To change the value of a specific item, refer to the index number
To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
增加列表元素 Add list items
Append items 末位增加一个元素
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Insert items 指定位置增加一个元素
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Extend list 指定位置增加多个元素
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
Add Any Iterable 可以增加任意类型的可迭代对象
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
Remove List Items 删除列表元素
Remove Specified Item 删除指定元素
The remove() method removes the specified item
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Remove Specified Index 删除指定索引元素
The pop() method removes the specified index.
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
Clear the List 清空列表
The clear() method empties the list.
The list still remains, but it has no content.
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)