message="Hello World!"
#Hello World!赋值给变量message
print(message)
输出:Hello World!
#用引号(“ ”)括起来的
首字母大写
.title( )
全部大写/小写
.upper( ) /.lower( )
message="hello world!"
print(message.title())
#对变量message执行方法.title()
输出:Hello World!
使用加号(+)来合并字符串
first_name="li"
last_name="ming"
full_name=first_name+" "+last_name
#变量名不用带""
print("Hello,"+full_name+"!")
输出:Hello,li ming!
换行符
\n
制表符(缩进)
\t
print("Languages:\n\t Python \n\t Java")
输出:
Languages:
Python
Java
两端
.Strip( )
左/右
.lstrip( ) / .rstrip( )
name=" li "
name=name.strip()
#必须将删除操作结果存回变量中
print(name)
输出:li
加(+)减(-)乘(*)除(/)
乘方(**)
age=18
message="Happy"+str(age)+"rd Brithday!"
#调用函数str(),将23转换成字符串值表示
print(message)
输出:Happy 18rd Brithday!
#用方括号([ ])括起来的,用逗号( ,)隔开元素。
kouhao=['中','国','加','油']
print(kouhao[0])
#第一个列表的索引值为0
输出:中
kouhao=['zhong','guo','jia','you']
message="Kouhao fist word is"+kouhao[0].title()+"."
print(message)
输出:kouhao first word is Zhong.
kouhao=['美','国']
kouhao[0]='中'
#先指定列表名和元素索引值,再赋予新值
print(kouhao)
输出:['中','国']
末尾/空列表
.append( )
插入
.insert( )
#append
kouhao=[]
#创建一个空列表,再赋值
kouhao.append('中')
kouhao.append('国')
print(kouhao)
输出:['中','国']
#insert
kouhao=['中']
kouhao.insert(1,'国')
#指定新元素的索引值和值
print(kouhao)
输出:['中','国']
已知删除元素的位置
del
已知删除元素的值
.remove( )
删除列表元素(默认末尾)
.pop( )
#del
zimu=['a','b','c']
del zimu[0]
#条件是知道其索引
print(zimu)
输出:['b','c']
#remove
zimu=['a','b','c']
zimu_1=zimu.pop(2)
#设新变量1存储被删除元素,被删除元素还可继续使用
#条件是知道其索引
print(zimu)
print("这道题选"+zimu_1+".")
输出:['a','b']
输出:这道题选c.
#remove
zimu=['a','b','c']
zimu.remove('b')
#条件是知道其值
print(zimu)
输出:['a','c']
#remove
zimu=['a','b','c']
zimu_2='b'
zimu.remove(zimu_2)
print(zimu)
print("这道题选"+zimu_2+".")
输出:['a','c']
输出:这道题选b.
按字母顺序
.sort( )
按字母倒序
.sort( reverse=True)
zimu=['b','d','a','c']
zimu.sort()
print(zimu)
输出:['a','b','c','d']
按字母顺序
.sorted( )
按字母倒序
.sorted( reverse=True)
.reverse( )
恢复原来顺序,再次调用reverse即可
zimu=['b','d','a','c']
zimu.reverse()
print(zimu)
输出:['c','a','d','b']
len( )
zimu=['b','d','a','c']
len(zimu)
输出:4
kemus=['yuwen','shuxue','yingyu']
#从列表kemus中取出一个元素存储在变量kemu中
for kemu in kemus:
#打印变量中的值,并再次进行for循环
print(kemu)
print("我最喜欢的科目是"+kemu[0]+".")
#避免缩减错误
输出:yuwen
shuxue
yingyu
我最喜欢的科目是yuwen.
range( )
for value in range(1,5):
#从第一个值开始,到指定值前一个停止
print(value)
输出:1
2
3
4
for value in range(1,5,2):
#指定步长
print(value)
输出:2
4
list( )
numbers=list(range(1,6))
#利用函数list将range的结果转为列表
print(numbers)
输出:[1, 2, 3, 4, 5]
squars=[]
for value in range(1,6):
#遍历生成一组数字
square = value**2
#计算这组数字数值的平方,并存储到变量square中
squares.append(square)
#将变量square中的结果添加到squares中
print(squares)
输出:[1,4,9,16,25]
最小值
min( )
最大值
max( )
总和
sum( )
numebers=[1,2,3,4,5]
min(numbers)
输出:1
quares = [value**2 for value in range(1,6)]
#表达式value**生成要存储到列表中的值
#for value in range(1,11)给表达式提供值
print(squares)
输出:[1,4,9,16,25]
squares=[0,1,2,3,4,5]
print(squares[0:3])
#第一个元素索引值及最后一个元素索引值:
输出:[0,1,2]
squares=[0,1,2,3,4,5]
print(squares[ :2])
#没有指定,默认起始索引值为第一个元素
输出:[0,1]
squares=[0,1,2,3,4,5]
print(squares[3:])
#没有指定,默认终止索引值为最后一个元素
输出:[3,4,5]
kemus=['yuwen','shuxue','yingyu']
for kemu in kemus[ :2]:
print(kemu)
输出:yuwen
shuxue
kemus=['yuwen','shuxue','yingyu']
kumus_2=kemus[ : ]
#从列表kemus中提取一个切片,创建列表副本
#将副本赋值给新列表kumus_2
print(kumus_2)
输出:['yuwen','shuxue','yingyu']
#用括号()括起来的
yuanzu=(250,50)
print(yuanzu[0])
输出:250
yuanzus=(250,50)
for yuanzu in yuanzus:
print(yuanzu)
输出:250
50
#元组不可修改,但可以重新赋值,达到修改的目的
yuanzus = (200, 50)
print("修改前:")
for yuanzu in yuanzus:
print(yuanzu)
yuanzus= (400, 100)
print("\n修改后:")
for yuanzu in yuanzus:
print(yuanzu)
输出:
修改前:
200
50
修改后:
400
100
#由键-值对组成,每个键都与一个值相关联。
#用大括号({ })括起来,键值之间用冒号( :)隔开,键值对之间用逗号( ,)隔开。
alient= {'color': 'green'}
print(alient['color'])
#指定字典名和键,输出对应的值
输出:green
alient= {'color': 'green'}
alient['points']=5
print(alient)
输出:{'color': 'green', 'points': 5}
alient= {'color': 'green'}
alient['color']='yelow'
输出:alient= {'color': 'yellow'}
del
alient= {'color': 'green','points':'5'}
del alient['points']
print(alient)
输出:{'color': 'green'}
for key.value in 字典名.items( ) :
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")
输出:Jen's favorite language is Python.
Sarah's favorite language is C.
Phil's favorite language is Python.
Edward's favorite language is Ruby.
for key in 字典名.keys( ) :
for name in favorite_languages.keys():
print(name.title())
输出:Jen
Sarah
Phil
Edward
for key in sorted(字典名.keys( )) :
for name in sorted(favorite_languages.keys()):
print(name.title())
输出:Edward
Jen
Phil
Sarah
for value in 字典名.values( ) :
for language in favorite_languages.values():
print(language.title())
输出:Python
C
Python
Ruby
for value in set(字典名.values( ) ):
for language in set(favorite_languages.values()):
print(language.title())
输出:Python
C
Ruby
alien_0 = {'color': 'green'}
alien_1 = {'color': 'yellow'}
alien_2 = {'color': 'red'}
#创建三个字典,字典中包含外星人的信息
aliens = [alien_0, alien_1, alien_2]
#创建一个外星人列表,把字典放进列表中
for alien in aliens:
print(alien)
#遍历列表
输出:{'color': 'green'}
{'color': 'yellow'}
{'color': 'red'}
# 创建一个空列表
aliens = []
# 创建5个绿色的外星人
for alien_number in range(5):
alien = {'color': 'green', 'points': 5}
#将其附加到列表aliens
aliens.append(alien)
#打印列表
for alien in aliens:
print(alien)
输出:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5}
# 创建一个空列表
aliens = []
# 创建5个绿色的外星人
for alien_number in range(5):
alien = {'color': 'green', 'points': 5}
#将其附加到列表aliens
aliens.append(alien)
#遍历切片,用if语句来确保只修改前三个绿色外星人。如果是绿色,就将其颜色为黄色。
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
#将黄色外星人改为值15个点。
elif alien['color'] == 'green':
alien['points'] = 15
for alien in aliens[0:5]:
print(alien)
输出:
{'color': 'yellow', 'points': 5}
{'color': 'yellow', 'points': 5}
{'color': 'yellow', 'points': 5}
{'color': 'green', 'points': 15}
{'color': 'green', 'points': 15}
#在字典favorite_languages中,存储了有关同学及相关科目的信息
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c']
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
#在遍历字典中,需再用一个for循环来遍历语言列表:
for language in languages:
print("\t" + language.title())
输出:
Jen's favorite languages are:
Python
Ruby
Sarah's favorite languages are:
C
#定义字典users,包含两个键:用户名'xiaoming'和'xiaohong',键的值是一个字典,包姓名和居住地
users = {
'xioaming': {
'name': 'albert',
'location': 'princeton',
},
'xiaohong': {
'name': 'marie',
'location': 'paris',
},
}
#遍历字典users,将键存储在变量username中,将值的字典存储在变量user_info中
for username, user_info in users.items():
print("\nUsername: " + username)
location = user_info['location']
print("\tName: " + name.title())
print("\tLocation: " + location.title())
输出:
Username: aeinstein
Name: Albert
Location: Princeton
Username: mcurie
Name: Marie Curie
Location: Paris