python语法基础#1

print('1')

关于字符串处理

a = 'apple' # title可以让单词首字母大写
print(a.title())
Apple
name = "Ada Lovelace" 
print(name.upper())#全部大写 
print(name.lower()) #全部小写
ADA LOVELACE
ada lovelace
print('mzl\nkkk')#3.要在字符串中添加换行符,可使用字符组合
mzl
kkk
#还可在同一个字符串中同时包含制表符和换行符。
#字符串"\n\t"让Python换到下一行,并在 下一行开头添加一个制表符。
print('mzl\n\tkkk')
print('mzl\tlaji')
#制表符的写法是\t,作用是对齐表格的各列。
print("学号\t姓名\t语文\t数学\t英语")
print("2017001\t曹操\t99\t88\t0")
print("2017002\t周瑜\t92\t45\t93")
print("2017008\t黄盖\t77\t82\t100")

mzl
	kkk
mzl	laji
学号	姓名	语文	数学	英语
2017001	曹操	99	88	0
2017002	周瑜	92	45	93
2017008	黄盖	77	82	100
#Python能够找出字符串开头和末尾多余的空白。要确保字符串末尾没有空白,可使用方法 rstrip(chars)。 
#chars -- 指定删除的字符(默认为空格)
mame ='python   '
name = name.rstrip()
print(name)
name.rstrip('n')
#你还可以剔除字符串开头的空白,或同时剔除字符串两端的空白。为此,可分别使用方法 lstrip()和strip()

python





'pytho'
age = 23 
message = 'Happy '+str(age)+'rd birthday'
print(message)
Happy 23rd birthday

关于list的处理

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles) 
motorcycles[0] = 'ducati' #修改第0个元素
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
#append将元素添加到末尾
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.append('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']
motorcycles = ['honda', 'yamaha', 'suzuki'] 
motorcycles.insert(0, 'ducati') #(先是位置,再是元素)
print(motorcycles)

['ducati', 'honda', 'yamaha', 'suzuki']
motorcycles = ['honda', 'yamaha', 'suzuki'] 
del motorcycles[0]
#使用list()将其他数据类型转化为列表
list('cat')
['c', 'a', 't']
#spilt('str')可将字符串切成若干子列表
birthday = '1/6/1952' 
print(birthday.split('/')) 
#如果出现连续空元素,则会出现空格
splitme = 'a/b//c/d///e' 
splitme.split('/') 

['1', '6', '1952']
['a', 'b', '', 'c', 'd', '', '', 'e']
marxes = ['Groucho', 'Chico', 'Harpo']
marxes[-2]
'Chico'
marxes = ['Groucho', 'Chico', 'Harpo']
marxes[0:2]#前闭后开
['Groucho', 'Chico']
marxes[::2]#步长为2提取元素
['Groucho', 'Harpo']
marxes[::-1] #实现元素逆序
['Harpo', 'Chico', 'Groucho']
#使用extend合并列表
others = ['Groucho','Chico','Harpo']
marxes = ['Groucho', 'Chico', 'Harpo']
marxes.extend(others)
print(marxes)
['Groucho', 'Chico', 'Harpo', 'Groucho', 'Chico', 'Harpo']
#使用+合并列表
others = ['Groucho','Chico','Harpo']
marxes = ['Groucho', 'Chico', 'Harpo']
others+marxes
['Groucho', 'Chico', 'Harpo', 'Groucho', 'Chico', 'Harpo']
#使用del删除元素
marxes = ['Groucho', 'Chico', 'Harpo']
del marxes[-1]
print(marxes)
['Groucho', 'Chico']
#使用remove()删除具有指定值的元素
marxes = ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo']
marxes.remove('Gummo')
print(marxes)
['Groucho', 'Chico', 'Harpo', 'Zeppo']
#使用pop()获取并删除指定位置的元素 
marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo']
print(marxes.pop())
print(marxes)
#如果你为 pop() 指定了偏移量,它会返回偏移量对应位置的元素;
#如果不指定,则默认使 用 -1。因此,pop(0) 将返回列表的头元素,而 pop() 或 pop(-1) 则会返回列表的尾元素
Zeppo
['Groucho', 'Chico', 'Harpo']
#使用index()查询具有特定值的元素位置
marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo']
marxes.index('Chico')
1
#使用in判断值是否存在
marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] 
'Groucho' in marxes
True
# 使用count()记录特定值出现的次数 
marxes = ['Groucho', 'Chico', 'Harpo'] 
marxes.count('Harpo')
 
1
#使用join()转换为字符串
marxes = ['Groucho', 'Chico', 'Harpo']
a =','.join(marxes)
print(a)
Groucho,Chico,Harpo
a.split(',')#逆过程
['Groucho', 'Chico', 'Harpo']
# 使用sort()重新排列元素
"""使用sort()会改变原来内容,
sorted()则不会改变"""
marxes = ['Groucho', 'Chico', 'Harpo'] 
sorted_marxes = sorted(marxes) 
print(sorted_marxes)
['Chico', 'Groucho', 'Harpo']

del 删除指定位置的元素

numbers = [1,5,0.3,6.0,4.9]
del numbers[-1]
print(numbers)
[1, 5, 0.3, 6.0]
numbers = [1,5,0.3,6.0,4.9]
numbers.sort()
print(numbers) #按照从大到小的顺序
[0.3, 1, 4.9, 5, 6.0]
#reverse=True可以改为降序排列
numbers = [1,5,0.3,6.0,4.9]
numbers.sort(reverse = True)
print(numbers)
[6.0, 5, 4.9, 1, 0.3]
#len()可以获取列表长度
#用=赋值,使用copy()复制 
a = [1,2,3]
b = a
a[0]='sb'
b
['sb', 2, 3]
a = [1,2,3]
b = a.copy()
c=a[:]
a[0]='sb'
print(b)
print(c)
[1, 2, 3]
[1, 2, 3]

关于dict的知识

#使用dict转化为字典
lol = [['a','b'],['b','c'],['c','d']]
dict(lol)
{'a': 'b', 'b': 'c', 'c': 'd'}
#使用update合并字典
pythons ={'Cleese': 'John','Gilliam': 'Terry','Palin': 'Michael','Chapman': 'Graham','Idle': 'Eric','Jones': 'Terry'}
others = { 'Marx': 'Groucho', 'Howard': 'Moe' } 
pythons.update(others)
pythons
{'Cleese': 'John',
 'Gilliam': 'Terry',
 'Palin': 'Michael',
 'Chapman': 'Graham',
 'Idle': 'Eric',
 'Jones': 'Terry',
 'Marx': 'Groucho',
 'Howard': 'Moe'}
#如果待添加的字典与待扩充的字典包含同样的键会怎样?是的,新归入字典的值会取代原有的值
first = {'a':1,'b':2}
second = {'b':'platypus'}
first.update(second)
first
{'a': 1, 'b': 'platypus'}
#使用del删除具有指定键的元素
del pythons['Marx'] 
pythons # 这里与list的操作一样
{'Cleese': 'John',
 'Gilliam': 'Terry',
 'Palin': 'Michael',
 'Chapman': 'Graham',
 'Idle': 'Eric',
 'Jones': 'Terry',
 'Howard': 'Moe'}

#使用clear()删除所有元素

#使用in判断是否存在 
pythons = {'Chapman': 'Graham', 'Cleese': 'John', 'Jones': 'Terry', 'Palin': 'Michael'}
'Chapman'in pythons 
True
# 使用keys()获取所有键 
signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}
signals.keys() 
dict_keys(['green', 'yellow', 'red'])
#使用values()获取所有值 
list( signals.values() ) 
['go', 'go faster', 'smile for the camera']
# 使用items()获取所有键值对
list( signals.items() ) 
#会生成键值元组
[('green', 'go'), ('yellow', 'go faster'), ('red', 'smile for the camera')]
#使用copy进行新建复制
signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}
original_signals = signals.copy() 
signals['blue'] = 'confuse everyone' 
signals
{'green': 'go',
 'yellow': 'go faster',
 'red': 'smile for the camera',
 'blue': 'confuse everyone'}
original_signals
{'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}
#使用set()创建集合,你可以使用 set() 函数创建一个集合,或者用大括号将一系列以逗号隔开的值包裹起来
#使用set()将其他类型转换为集合 
set('letters')
{'e', 'l', 'r', 's', 't'}
#当字典作为参数传入 set() 函数时,只有键会被使用
set( {'apple': 'red', 'orange': 'orange', 'cherry': 'red'} ) 
{'apple', 'cherry', 'orange'}
#使用in测试值是否存在
drinks = {
     'martini': {'vodka', 'vermouth'},
     'black russian': {'vodka', 'kahlua'}, 
    'white russian': {'cream', 'kahlua', 'vodka'},
     'manhattan': {'rye', 'vermouth', 'bitters'}, 
     'screwdriver': {'orange juice', 'vodka'} 
}
for name,contents in drinks.items():
    if 'vodka' in contents:
        print(name)
martini
black russian
white russian
screwdriver

集合的计算

#合并及运算符 
#如果想要查看多个集合之间组合的结果应该怎么办?例如,你想要找到一种饮料,它含有 果汁或含有苦艾酒。我们可以使用交集运算符,记作 &:
for name , contents in drinks.items():
    if contents & {'vermouth','orange juice'}:
        print(name)
martini
manhattan
screwdriver
a = {1,2}
b = {2,3}
a&b
{2}
#交集
a.intersection(b)
{2}
#差集
a-b
{1}
a.difference(b)
{1}
#使用 ^ 或者 symmetric_difference() 可以获得两个集合的异或集(仅在两个集合中出现一次):
a^b
{1, 3}

程序在合理的长度下是易读的。一行程序的(非强制性)最大长度建议为 80 个字符。
如果你在该长度下写不完你的代码,可以使用连接符 \(反斜线)。把它放在一行的结
束位 置,Python 仍然将其解释为同一行。

关于循环

#使用if,elif,else进行比较
if True:
    print('yes')
else:
    print('no')
yes
coler = 'red'
corn = 'The coler is '
if coler == 'blue':
    print(corn+'blue')
elif coler == 'red':
    print(corn + 'red')
else:
    print("I can't guess")
I can't guess
num = [1,2,3]
if 1 in num:
    print('y') #前边if判断成功,后面elif则不判断
elif 2 in num:
    print('n')
y

important_dict ={
‘等于’ :’==’,
‘不等于’: ‘!=’
}"""如果表达式的返回类型不是布尔会发生什么?什么情况下 Python 会认为是 True 和 False?
一个成假赋值不一定明确表示为 False,下面的情况也会被认为是 False

#除法'/'
2/6
0.3333333333333333
#整除
9//5
1

python代码中的进制表示
注意:0b后面才是数字

10
10
0b10#二进制
2
0o10#八进制
8
0x10#十六进制
16

使用\进行转义

最常见的转义符是 \n,它代表 换行符,便于你在一行内创建多行字符串。
转义符 \t(tab 制表符)常用于对齐文本,之后会经常见到

palindrome = 'A man ,\nA plan,\nA canal:\nPanama'
print(palindrome)
A man ,
A plan,
A canal:
Panama
print('\tabc')
print('a\tbc')
print('ab\tc')
print('abc\t')
	abc
a	bc
ab	c
abc	

使用[]提取字符

letters = 'abcdefghijklmnopqrstuvwxyz' 
letters[12]
'm'

使用[start🔚step]分片
• [:] 提取从开头到结尾的整个字符串
• [start:] 从 start 提取到结尾
• [:end] 从开头提取到 end - 1 • [start:end] 从 start 提取到 end - 1
• [start🔚step] 从 start 提取到 end - 1,每 step 个字符提取一个

continue,break,while与循环

#使用while进行循环
count = 1 
while count <= 5:
    print(count)
    count += 1
1
2
3
4
5
#使用break跳出循环
count = 1
while count <= 5:
    print(count)
    count +=1
    if count == 3 :
        break 
1
2
count = 1
while count <= 5:
    count +=1
    if count == 3:
        continue # 回到循环开始
    print(count)
2
4
5
6
c = 1 
while c<=5:
    print(c)
    c+=1
    if c==4:
        break
1
2
3
#循环外使用else
list1 = [1,9,7,13]
position = 0
while position < len(list1):
    n = list1[position]
    if n % 2 ==0 :
        print('found even number %d'%n)
        break
    position += 1
else:
    print('found no even number')
    

found no even number
#使用zip()并行迭代 
days = ['Monday', 'Tuesday', 'Wednesday']
fruits = ['banana', 'orange', 'peach'] 
drinks = ['coffee', 'tea', 'beer'] 
print(list(zip(days,fruits,drinks)))
print(dict(zip(days,fruits)))
[('Monday', 'banana', 'coffee'), ('Tuesday', 'orange', 'tea'), ('Wednesday', 'peach', 'beer')]
{'Monday': 'banana', 'Tuesday': 'orange', 'Wednesday': 'peach'}

有关函数

# Python 处理参数的方式要比其他语言更加灵活。其中,最熟悉的参数类型是位置参数,传 入参数的值是按照顺序依次复制过去的。
def menu(wine, entree, dessert): 
     return {'wine': wine, 'entree': entree, 'dessert': dessert} 
menu('chardonnay', 'chicken', 'cake')  
{'wine': 'chardonnay', 'entree': 'chicken', 'dessert': 'cake'}
# 为了避免位置参数带来的混乱,调用参数时可以指定对应参数的名字,甚至可以采用与函 数定义不同的顺序调用
menu(entree='beef', dessert='bagel', wine='bordeaux')
{'wine': 'bordeaux', 'entree': 'beef', 'dessert': 'bagel'}
# 指定默认参数值 
def menu(wine, entree, dessert='pudding'):
     return {'wine': wine, 'entree': entree, 'dessert': dessert}
menu('chardonnay', 'chicken') 
{'wine': 'chardonnay', 'entree': 'chicken', 'dessert': 'pudding'}
# 使用*收集位置参数
def print_args(*args): 
    print('this is an args:',args)
print_args()
this is an args: ()
print_args(3, 2, 1, 'wait!', 'uh...')
# 会把元组打印出来
# 这样的技巧对于编写像 print() 一样接受可变数量的参数的函数是非常有用的。
this is an args: (3, 2, 1, 'wait!', 'uh...')
# 使用**收集关键字参数 
def print_kwargs(**kwargs):
    print('Keyword arguments:', kwargs) 
print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')
#使用两个星号可以将参数收集到一个字典中,参数的名字是字典的键,对应参数的值是字 典的值。
Keyword arguments: {'wine': 'merlot', 'entree': 'mutton', 'dessert': 'macaroon'}
#一等公民:函数
def answer():
    print(42)
answer()
42
def run_something(func):
    func()
run_something(answer)
42
# 内部函数可以看作一个闭包。闭包是一个可以由另一个函数动态生成的函数,并且可以改 变和存储函数外创建的变量的值。
def outer(a,b):
    def inner (c,d):
        return c+d
    return inner (a,b)
outer(4,7)
11
# 匿名函数:lambda()函数 
def edit_story (words,func) :
    for word in words :
        print(func(word))
stairs = ['thud', 'meow', 'thud', 'hiss']
edit_story (stairs,lambda word : word.capitalize()+'!')

Thud!
Meow!
Thud!
Hiss!

lambda 的格式:
lambda + 输入参数 +":"+返回值

生成器

生成器是用来创建 Python 序列的一个对象。使用它可以迭代庞大的序列,且不需要在内 存中创建和存储整个序列。通常,生成器是为迭代器产生数据的。回想起来,我们已经在 之前的例子中使用过其中一个,即 range(),来产生一系列整数。range() 在 Python 2 中 返回一个列表,这也限制了它要进入内存空间。Python 2 中同样存在的生成器 xrange() 在 Python 3 中成为标准的 range() 生成器。这个例子累加从 1 到 100 的整数:
sum(range(1, 101))
5050
每次迭代生成器时,它会记录上一次调用的位置,并且返回下一个值。这一点和普通的函 数是不一样的,一般函数都不记录前一次调用,而且都会在函数的第一行开始执行。
如果你想创建一个比较大的序列,使用生成器推导的代码会很长,这时可以尝试写一个 生成器函数。生成器函数和普通函数类似,但是它的返回值使用 yield 语句声明而不是return。下面编写我们自己的 range() 函数版本:

def my_range(first = 0 , last = 10 ,step = 1):
    number = first
    while number < last :
        yield number
        number += step
print(list(my_range()))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#可以对这个生成器对象进行迭代:
for x in my_range():
    print(x,end= ' ')
0 1 2 3 4 5 6 7 8 9 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值