编码情况、保留小数、字符串格式化、round函数、re正则匹配模块
'''默认情况下,Python 源文件是 UTF-8 编码。
在此编码下,全世界大多数语言的字符可以同时用在字符串、标识符和注释中
— 尽管 Python 标准库仅使用 ASCII 字符做为标识符,这只是任何可移植代码应该遵守的约定。
如果要正确的显示所有的字符,你的编辑器必须能识别出文件是 UTF-8 编码,
并且它使用的字体能支持文件中所有的字符。
你也可以为源文件指定不同的字符编码。为此,在 #! 行(首行)后插入至少一行特殊的注释行来定义源文件的编码:
# -*- coding: encoding -*-
通过此声明,源文件中所有的东西都会被当做用 encoding 指代的 UTF-8 编码对待。
在 Python 库参考手册 codecs 一节中你可以找到一张可用的编码列表。
例如,如果你的编辑器不支持 UTF-8 编码的文件,但支持像 Windows-1252 的其他一些编码,你可以定义:
# -*- coding: cp-1252 -*-
这样就可以在源文件中使用 Windows-1252 字符集中的所有字符了。
这个特殊的编码注释必须在文件中的 第一或第二 行定义。'''
print("Hello World!")
message = "Hello python world"
print(message)
message = "Hello Python World!"
保留小数
x = 3.1415926
print("%.2f"%x)
print("{:.2f}".format(x))
print(round(x,3))
from decimal import Decimal
a = Decimal(x).quantize(Decimal("0.00000"))
print(a)
a = str(x).split(".")[0]+"."+str(x).split(".")[1][:3]
print(a)
import re
a = re.findall(r"\d{1,}?\.\d{2}",str(a))
print(a)
不换行,斐波那契子序列
a,b = 0,1;
while b < 10:
print(b,end = "")
a,b = b,a+b
5**2计算幂乘方
x = 2**3
y = 3 + 5j
z = 2 + 6J
print(x)
print(y+z)
print(5//2)
2.变量和简单数据类型
修改大小写 合并(拼接)字符串 #添加空白 #暂时删除空格、rstrip()删头空白、lstrip()删尾空白、strip()删头尾空白 代码如下(示例):
修改大小写
print("I told my friend,'Python is my favorite language!'\n")
name = "ada lovelace"
print(name.title())
print(name.lower())
print(name.upper())
合并(拼接)字符串
first_name = "Abc"
last_name = "def"
full_name = first_name+""+last_name
print(full_name)
full_name = first_name+" "+last_name
print(full_name)
添加空白
print("Python")
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")
暂时删除空格、rstrip()删头空白、lstrip()删尾空白、strip()删头尾空白
language = 'Python '
print(language)
language = language.rstrip()
print(language)
使用函数str()避免类型错误
age = 18
message = "Happy " + str(age) + "th Birthday!"
print(message)
3.列表简介
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
print(bicycles[-1])
print("\n")
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
print("\n")
bicycles[0] = "a"
print(bicycles)
print("\n")
在最后加元素:append
bicycles.append('bbq')
print(bicycles)
print("\n")
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
print("\n")
插入->everywhere:insert
motorcycles.insert(0,'ducadi')
print(motorcycles)
print("\n")
删除->qu.everywhere:del
del motorcycles[0]
print(motorcycles)
print("\n")
删掉最后一个
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
print("\n")
删除
abo = ['abc','w','qw']
pop_abo = abo.pop(0)
print(pop_abo)
print(abo)
print("\n")
motor = ['honda','yamaha','suzuki','ducati']
print(motor)
motor.remove('yamaha')
print(motor)
too_expensive = 'ducati'
motor.remove('ducati')
print(motor)
print("\nA " + too_expensive + " is too expensive for me")
print("\n")
组织列表
cars = ["bmw",'audi','toyota','subatu']
cars.sort()
print(cars)
cars.sort(reverse = True)
print(cars)
print("\n")
cars = ["bmw",'audi','toyota','subatu']
print(sorted(cars))
print(cars)
print(sorted(cars,reverse = True))
print(cars)
print("\n")
cars.reverse()
print(cars)
print(len(cars))
4.列表操作
包含列表各种操作
magicions = ['alice','david','carolina']
for magicion in magicions:
print(magicion.title()+",that was a great trick!")
print("Thank you,everyone,that's agreat magic show!")
for value in range(3,8):
print(value)
numbers = list(range(2,6))
print(numbers)
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
digits = [3,5,6,2,7,1,8,0]
print(min(digits))
print(max(digits))
print(sum(digits))
squares = [value**2 for value in range(1,11)]
print(squares)
print(squares[2:5])
print(squares[:2])
print(squares[3:])
print(squares[-3:])
for abc in squares[:-3]:
print(abc)
my = ['fgh','hji','uui','qqw','rre','tty']
food = my[:]
print(food)
print("The first three items in the list are:")
print(my[:3])
dimonsions = (200,50)
for dimonsion in dimonsions:
print(dimonsion)
dimonsions = (400,60)
print(dimonsions[0])
5.if语句
包含列表各种操作
>>> a = 2
>>> b = 4
>>> a >= 0 and b < 1
False
>>>
age_0 = 3
age_1 = 6
if (age_0 >= age_1) :
print(age_0)
else:
print(age_1)
requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding.")
if 'cabbage' not in requested_toppings:
print("Sorry,we don't have it.")
print("\n")
alien_color = 'yellow'
if alien_color == 'green':
print("You have got 5 points.")
elif alien_color == 'yellow':
print("You have got 10 points.")
else :
print("You have got 15 points.")
available = ['mushrooms','olives','green peppers','pepproni','pineapple','extra cheese']
requests = []
print("Please input 3 kinds of needs.\n")
for i in range(3):
print("please input")
temp = input()
requests.append(temp)
print(requests)
for request in requests:
if request in available:
print("Adding" + request + ".")
else:
print("Sorry,we don't have " + request + ".")
print("Finished making your pizza!")
6.字典
字典相关操作,字典列表等包含列表各种操作
alien_0 = {"color":"green",'point':5}
print(alien_0['color'])
print(alien_0['point'])
newpoint = alien_0['point']
print("You just earned "+str(newpoint)+" points!")
print("\n")
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
alien_0['color'] = 'yellow'
print(alien_0)
del alien_0['point']
print(alien_0)
user_0 = {'username':'efermi','first':'enrico','last':'fermi'}
for key,value in user_0.items():
print("\nkey:"+key)
print("Value:"+value)
print('\n')
favorite_language = {'jen':'python','sarah':'c','edward':'ruby','phil':'python'}
for name,language in favorite_language.items():
print(name.title()+"'s favorite langusge is "+language.title()+".")
for name in favorite_language.keys():
print(name.title())
for name in sorted(favorite_language.keys()):
print(name.title()+",thamk you for taking the poll.")
print("\n")
favorite_language = {'jen':'python','sarah':'c','edward':'ruby','phil':'python'}
print("The following languages have been mentioned:")
for language in favorite_language.values():
print(language.title)
for language in set(favorite_language.values()):
print(language.title)
alien_0 = {'color':'green','points':'5'}
alien_1 = {'color':'yellow','points':'10'}
alien_2 = {'color':'red','points':'15'}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
print('\n')
aliens = []
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['apeed'] = 'fast'
alien['points'] = 15
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens: "+str(len(aliens)))
print("\n")
pizza = {
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
print('You ordered a '+pizza['crust']+'-crust pizza '+'with the following toppings:')
for topping in pizza['toppings']:
print('\t'+topping)
favorite_languages = {
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell'],
}
for name,languages in favorite_languages.items():
if(len(languages) == 1):
print("\n"+name.title()+"'s favorite language is:")
else:
print("\n"+name.title()+"'s favorite languages are:")
for language in languages:
print("\t"+language.title())
在字典存储
users = {
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton',
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris',
},
}
for username,user in users.items():
print("\nUsername:"+username)
full_name = user['first']+' '+user['last']
location = user['location']
print("\tFull name:"+full_name.title())
print("\tLocation:"+location.title())
例子
cities = {
'beijing':{
'country':'China',
'population':'a',
'fact':'o',
},
'New York':{
'country':'America',
'population':'b',
'fact':'p',
},
'Paris':{
'country':'France',
'population':'c',
'fact':'q',
},
}
for CityName,city in cities.items():
print("\ncity:"+CityName)
country = city['country']
population = city['population']
fact = city['fact']
print("\tcountry:"+country.title())
print("\tpopulation:"+population.title())
print("\tfact:"+fact.title())
相关资料整理
1.简单操作 2.变量和简单数据类型 3.列表简介 4.列表操作 5.if语句 6.字典
|