python基础(一)
Python基础知识
一 、注释
1.1单行注释(用#表示)
# 单行注释,这里就是一行注释
1.2多行注释(用三个引号)
"""
多行字符串可以用三个引号包裹,单引号和双引号都可以
这里就是多行注释
再来一行
"""
二、数据类型
2.1.数据类型:
不可变的数据类型:
number:int,float,complex
bool: True,False
str: 字符串
tuple: 元组
None: 空值
可变数据类型:
list:列表
dict:字典
set:集合
2.2基本操作
①字符串:
定义字符串:
s = “hello”
- 基本操作:
拼接:+
a = "hello"
b = "world"
print(a+b)
切片:[:]
b = "Hello, World!"
print(b[2:5])
字符串长度
b = "Hello, World"
print(len(b))
strip() 方法删除开头和结尾的空白字符
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
lower() 返回小写的字符串:
a = "Hello, World!"
print(a.lower())
upper() 方法返回大写的字符串:
a = "Hello, World!"
print(a.upper())
split() 方法在找到分隔符的实例时将字符串拆分为子字符串:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
使用 format() 方法格式化输出:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
②列表
创建列表
thislist = ["apple", "banana", "cherry"]
print(thislist)
遍历列表
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
列表长度
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
使用 append() 方法追加项目
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
在指定的索引处添加项目,使用 insert() 方法
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
删除项目
- remove()方法,删除指定的项目
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
- pop()方法,删除指定的索引(如果未指定索引,则删除最后一项)
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
sorted()对列表进行排序
L = [8,2,50,3]
print(sorted(L))
③字典
创建并打印字典:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
print(thisdict)
遍历字典
逐个打印字典中的所有键名:
for x in thisdict:
print(x)
逐个打印字典中的所有值:
for x in thisdict:
print(thisdict[x])
使用 values() 函数返回字典的值:
for x in thisdict.values():
print(x)
使用 items() 函数遍历键和值:
for x, y in thisdict.items():
print(x, y)
添加项目:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
thisdict["color"] = "red"
print(thisdict)
删除项目:
pop() 方法删除具有指定键名的项:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
thisdict.pop("model")
print(thisdict)
del 关键字也可以完全删除字典:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
del thisdict
print(thisdict) #this 会导致错误,因为 "thisdict" 不再存在。
复制字典
copy()方法:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
mydict = thisdict.copy()
print(mydict)
使用 dict() 方法创建字典的副本:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
mydict = dict(thisdict)
print(mydict)