Python语法基础(字符串、列表、切片和元组)


(新手小白自学python,留此文章,便于日后温故知新)


一、变量和简单数据类型

1.1 第一个程序

#输出Hello Python world!
print("Hello Python world!")

1.2 变量和字符串

1.2.1 变量

#message为一个变量
message=Hello Python world!
print(message)

1.2.2 字符串

在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。

#单引号、双引号均可表示字符串
"This is a string."
'This is also a string.'

#修改字符串大小写
name = "ada lovelace"
print(name.title())

#合并(拼接)字符串
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print("Hello, " + full_name.title() + "!")

#制表符换行符添加空格,\t为制表符、\n为换行符
>>> print("Python")
Python
>>> print("\tPython")
     Python
>>> print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C 
JavaScript

#字符串"\n\t" 让Python换到下一行,并在下一行开头添加一个制表符
>>> print("Languages:\n\tPython\n\tC\n\tJavaScript")
     Languages:
     Python
     C
     JavaScript
     
#删除空白格
>>> favorite_language = ' python '
>>> favorite_language.rstrip() #剔除右空格
>>> favorite_language.lstrip() #剔除左空格
>>> favorite_language.strip() #剔除两端空格

1.3 数字和注释

#数字
>>> 2 + 3
5
>>> 3/2
1.5
>>> 3 ** 2   #Python使用两个乘号表示乘方运算
9
>>> (2 + 3) * 4
20

#浮点数
>>> 0.1 + 0.1
0.2
>>> 0.2 + 0.1    #结果包含的小数位数不确定
0.30000000000000004
>>> 3 * 0.1
0.30000000000000004

#函数str()可将非字符串值表示为字符串
>>>age = 23
>>>message = "Happy " + str(age) + "rd Birthday!"
>>>print(message)
Happy 23rd Birthday!
#Python中使用“#”标识注释

二、列表简介

列表由一系列按特定顺序排列元素组成,其中的元素之间可以没有任何关系。在Python中,用方括号([ ])来表示列表,并用逗号来分隔其中的元素。

2.1 创建列表

#列表示例
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
#打印结果:
['trek', 'cannondale', 'redline', 'specialized']

#访问列表元素(从列表bicycles中提取第一款自行车)
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0]) 
#输出结果:
trek  

#Python同C或C++一样,索引均从0开始
#下面的代码访问索引1和3处的自行车
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[1])
print(bicycles[3])
#输出结果(返回列表中的第二个和第四个元素):
cannondale
specialized

#通过将索引指定为-1 ,可让Python返回最后一个列表元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[-1])
#返回结果:
specialized

#可使用列表中的元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
#输出结果:
My first bicycle was a Trek.

2.2 修改、添加和删除元素

2.2.1 修改和添加元素

#修改列表元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
#输出结果:
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']

#添加列表元素
#方法append()将元素'ducati'添加到了列表末尾
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
#输出结果:
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']

#插入列表元素
#使用方法insert()可在列表的任何位置添加新元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
#输出结果:
['ducati', 'honda', 'yamaha', 'suzuki']

2.2.2 删除元素

#列表中删除元素
#使用del语句删除元素(知道待删除元素的索引,删除后不再使用该元素)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
#输出结果:
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']

#使用方法pop()删除元素(弹出列表末尾元素,删除后可接着使用此元素)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
#输出结果:
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki

#使用这种pop()方法时,可将列表视为一个栈,删除列表末尾的元素相当于弹出栈顶元素。
#也可使用pop(索引号)来删除列表中任何位置的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')
#输出结果:
The first motorcycle I owned was a Honda.

#根据值删除元素
#使用方法remove()来删除知道值的元素
#从列表motorcycles 中删除值'ducati'
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
#输出结果:
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

#使用remove()从列表中删除元素时,也可接着使用它的值
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA " + too_expensive.title() + " is too expensive for me.")
#输出结果:
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

A Ducati is too expensive for me.

2.3 组织列表

#使用方法sort()对列表进行永久性排序(不可恢复)
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
#输出结果:
['audi', 'bmw', 'subaru', 'toyota']

#向sort()方法传递参数reverse=True,可按与字母顺序相反的顺序排列列表元素(不可恢复)
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
#输出结果:
['toyota', 'subaru', 'bmw', 'audi']

#使用函数sorted()对列表进行临时排序(不影响原始排序)
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
#输出结果:
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']
#也可向函数sorted()传递参数reverse=True

#使用方法reverse()倒着打印列表(永久性反转列表元素的排列顺序)
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
#输出结果:
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

#使用函数len()获悉列表长度(列表长度为所含元素个数)
>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars)
4
#注:Python计算列表元素数时从1开始。

三、操作列表

3.1 遍历整个列表

#第二行表示从列表magicians中取出一个名字,并将其存储在变量magician中。
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
	print(magician)
#输出结果:
alice
david
carolina

#还可扩展示例
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
	print(magician.title() + ", that was a great trick!")
#输出结果:
Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!

#在代码行for之后,每行缩进的代码均为循环体的一部分
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
   print(magician.title() + ", that was a great trick!")
    print("I can't wait to see your next trick, " + magician.title() + ".\n")
#结果输出:
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

#在for循环之后,无缩进代码只执行一次,而非重复执行
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
   print(magician.title() + ", that was a great trick!")
   print("I can't wait to see your next trick, " + magician.title() + ".\n")
print("Thank you, everyone. That was a great magic show!")
#输出结果:
Alice,that was a great trick!
I can't wait to see your next trick,Alice.

David,that was a great trick!
I can't wait to see your next trick,David.

Carolina,that was a great trick!
I can't wait to see your next trick,Carolina.

Thank you, everyone. That was a great magic show!

对于位于for 语句后面且属于循环组成部分的代码行,一定要缩进。
当出现语法错误时,如for语句之后紧接的语句忘记缩进、缩进了无需缩进的代码行、出现了不符合语法的代码或遗漏了冒号,Python会提醒出错哦;
当出现逻辑错误时,如忘记缩进额外的代码行或者进行了循环后的不必要缩进,那Python就大概率不会提醒啦~

3.2 创建数值列表

#函数range()可轻松地生成一系列的数字(输出不包含函数地第二个值)
for value in range(1,5):
   print(value)
#输出结果:
1
2
3
4

#使用函数list()将range()的结果直接转换为列表。
numbers = list(range(1,6))
print(numbers)
#输出结果:
[1, 2, 3, 4, 5]

#在函数range()中可指定步长
#函数range()从2开始数,然后不断地加2,直到达到或超过终值11
even_numbers = list(range(2,11,2))
print(even_numbers)
#输出结果:
[2, 4, 6, 8, 10]

#将前10个整数的平方加入到一个列表中
squares = []
for value in range(1,11):
  square = value**2
  squares.append(square)
print(squares)
#输出结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

#也可更加简洁,输出结果同上
squares = []
for value in range(1,11):
  squares.append(value**2)
print(squares)

3.3 统计计算函数与列表解析

3.3.1 统计计算函数

#找出数字列表的最小值、最大值和总和
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45

3.3.2 列表解析

列表解析是指将for循环和创建新元素的代码合并成一行,并自动附加新元素,即只需编写一行代码就能生成以上示例的列表。

#方法一
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)

#方法三(列表解析)
squares=[value**2 for value in range(1,11)]
print(squares)

#以上三种输出结果相同,均为[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

3.4 切片和遍历切片

处理列表中的部分元素,即使用列表的一部分,在python中称为切片

3.4.1 切片

#创建切片时,可指定要使用的第一个元素和最后一个元素的索引
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
#输出结果:
['charles', 'martina', 'michael']

#提取列表的第2~4个元素,可将起始索引指定为1 ,并将终止索引指定为4
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])
#输出结果:
['martina', 'michael', 'florence']

#未指定第一个索引时,Python将自动从列表开头开始
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
#输出结果:
['charles', 'martina', 'michael', 'florence']

#提取从第3个元素到列表末尾的所有元素时,将起始索引指定为2 ,并省略终止索引
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])
#结果返回从第3个元素到列表末尾的所有元素:
['michael', 'florence', 'eli']

#负数索引返回离列表末尾相应距离的元素,在切片中也可使用
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])
#上述代码打印最后三名队员的名字

3.4.2 遍历切片

#遍历列表中的部分元素
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
  print(player.title())
#输出结果:
Here are the first three players on my team:
Charles
Martina
Michael

3.5 复制列表

复制列表:具体操作是指创建一个包含整个列表切片,即同时省略起始索引和终止索引([:] )。这时,Python会创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。

#从列表my_foods中提取一个切片,从而创建了这个列表的副本,再将该副本存储到变量friend_foods中。
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
#输出结果:
My favorite foods are:
['pizza', 'falafel', 'carrot cake']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']

3.6 元组

Python将不能修改的值称为不可变的 ,而不可变的列表被称为元组。元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。

#定义元组
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
#输出结果:
200
50

#遍历元组中的所有值
dimensions = (200, 50)
for dimension in dimensions:
	print(dimension)
#输出结果:
200
50

#修改元组变量
#虽然不能修改元组的元素,但可以给存储元组的变量赋值(python中给元组变量赋值是合法的)
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
	print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
	print(dimension)
#输出结果:
Original dimensions:
200
50

Modified dimensions:
400
100

当存储的一组值在程序的整个生命周期内都不变时,可使用元组。

若电脑未配置环境,可配置后再进行学习,当然也可直接登录https://replit.com/进行python基础语法的学习。
以上为Python语法基础第一部分的内容,本文仅仅简单介绍了字符串、列表、切片和元组的使用方法及示例,余下的语法基础将在接下来的几篇文章中进行介绍。


社交有距春常在,核酸无恙岁月安。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值