python - for循环,字符串,元组基础

目录

for循环

字符串String

[元组 Tuple](#元组 Tuple)


今天在文学作品中学了一句"严于律己,宽以待人"的英文表达,

"He was austere with himself, but he had an approved tolerance for others"

【其实我没记住,翻开记录又看了一眼】

deepseek说这个表达太正式了,文学色彩浓厚,口语中使用会显得你太正经,所以它推荐了两种说法

"He's really hard on himself, but super understanding with other people."

"He's strict with himself, but really tolerant toward others"

想不起来了就看一眼~·~~

for循环

借助range函数来使用for循环

range()函数,可以理解为返回一个序列,便于理解,

但需要知道的是,实际上 rang()函数只会在需要的时候才返回序列中的下一个数字

向前计数:

range(10) 返回[0,9]的数列,可以理解为给rang()一个正数n,会返回一个[0,10)的序列

以五为单位进行计数:

rang(0, 50, 5), rang(起始点,结束点,计数单位),所以rang(0, 50, 5)会在[0, 50)中以5为计数单位返回序列[0,5,10,15,20,25...45]

向后计数:

rang(10, 0, -1)最后参数为-1,表示从起始点开始,通过每次加上-1的方式向结束点前进

python 复制代码
# Counter

# range(10)返回[0,9]的数列,可以理解为给rang()一个正数n,会返回一个[0,10)的序列
# 实际上 rang()函数只会在需要的时候才返回序列中的下一个数字
# 向前计数
print("Counting...")
for i in range(10) :
	print(i, end = " ")

# rang(0, 50, 5), rang(起始点,结束点,计数单位),所以rang(0, 50, 5)会在[0, 50)中以5为计数单位返回序列[0,5,10,15,20,25...45]
# 以五为单位进行计数
print("\n\nCounting by fives")
for i in range(0, 50, 5) :
	print(i, end = " ")


# rang(10, 0, -1)最后参数为-1,表示从起始点开始,通过每次加上-1的方式向结束点前进
# 向后计数
print("\n\nCounting backwards")
for i in range(10, 0, -1) :
	print(i, end = " ")

print("\n\nPress the enter key to exit.\n")

输出结果:

字符串String

字符串是由多个字符组成的序列,是不可变的。

理解不可变性

序列分为两种:可变的(mutable)和不可变的(immutable)

可变(mutable)是说序列可以被修改

不可变(immutable)是说序列不可以被修改

举个例子:

一个字符串

word = "aggregate"

word[0] = 'c' #【だめ 达咩, 不行】,不可变性!!!

word = "congregate" # 这个是给word重新赋值为了"congregate",而不是把之前的字符串"aggregate"给修改了

python提供了许多实用的函数和运算符用于操作字符串在内的各种序列。

len()函数,返回序列的长度,即序列所包含的元素数量(所有字符都包含在内,包括空格和感叹号之类)。

in , 判断某个元素是否是某个序列的成员, 如"if 'e' in message: " 就是判断e是不是message中的元素。

对字符串进行索引

名词解释:

顺序访问(sequential access):按顺序逐个字符访问。通过for循环,就是按顺序逐个字符地对字符串进行遍历。

随机访问(random access):直接从序列中获取任意位置的元素。 可以通过索引(index),指定序列中的一个位置编号,获取该位置上的元素。

python可以直接通过for循环遍历字符串的每一个字符

(java访问需要用chars() : word.chars().forEach(c -> System.out.println((char) c)); )

python 复制代码
import random

word = "austere"
print("The word is : ", word, "\n")

# 顺序访问
for i in word :
	print(i)

''' 
随机访问
random.randrange(low, high) 用于产生两个指定断点间的随机数
'''
# 创建两个端点
high = len(word) # 7
low = -len(word) # -7

# 创建一个能够执行10次的for循环
for i in range(10) :
	# 生产随机数,作为索引
	position = random.randrange(low, high)
	# word[position]通过索引读取该位置的元素
	print("word[", position ,"]\t",word[position])



print("\n\nPress the enter key to exit.\n")

执行结果:

"+" ,可以用于连接两个字符串,每用一次"+"连接符就创建一个新字符串

python 复制代码
message = input("Enter a message: ")
new_message = ""
VOWELS = "aeiou"

print()
for letter in message :
	if letter.lower() not in VOWELS :
		new_message += letter
		print("A new string has been created: ", new_message)

print("\n Your massage without vowels is : ", new_message)

输出结果:

切片:一次性获取序列中的一串连续元素

理解切片:序列[start:end:step]

word = "propaganda"
word[0:10]word[:]

获取所有字符 propaganda
word[2:10]word[2:]

获取下标2到最后的字符 opaganda
word[0:5]word[:5]

获取下标0~5的字符 propag
word[3:7] :获取下标3~7的字符 pagan
word[-8:-1] : 获取下标-8~-1的字符opagand 【word[-1:-8]不会输出任何字符】
word[0:6:3]:下标0~8每个3个取一个字符 ppa
word[::-1] : 反转字符串 adnagaporp

index(),用于查看某个字符在字符串中的下标

word = "propaganda"

print("p's index is : %s \na's index is : %s " % (word.index("p"), word.index("a")))

打印:

p's index is : 0

a's index is : 4

split(","),以逗号切割字符串为一个列表,分隔符可以自定义不一定是逗号,注意返回的是一个列表

word = "political propaganda "

wl = word.split(" ")

print(wl)

打印:['political', 'propaganda']

strip(字符串), 去除指定字符,会将参数字符串中的每一个字符都去掉。

如:

word = "propaganda"

print(word.strip("par"))

打印:opagand

count(字符串),参数字符串在原字符串中出现的次数

word = "propaganda"

print(word.count("p"))

打印:2

replace(old_el, new_el),得到一个新的字符串

word = "propaganda"

#注意 这里的word指向了新的字符串,而不是改变了"propaganda", 字符串是不可变的

word = word.replace("da", "dist")

print("new word is: ", word)

打印:new word is: propagandist

元组 Tuple

元组跟字符串一样,也是一种不可变序列 。与字符串不同的是,字符串只可以包含字符,而元组可以包含任意类型的元素,即一个元组中可以包含字符串、数字、图片、声音文件、甚至外星人(对象)等等。

元组的创建:

名称 = ()# 创建空元组

名称 = ( 1, "complexion",{"username": "liu", "age": 30}) # 创建带元素的元组

因为元组和字符串一样都是序列,所以字符串可用的函数,元组通用适用。

书中通过一个 英雄清单 的例子来演示元组的使用(最简单的例子,不考虑输入为空、数组越界等问题的处理)

python 复制代码
# Hero's Inventory
# 演示元组的创建及使用

#创建一个空的元组
inventory = ()

# 把元组当做条件来用
# 只要元组中各有一个元素就是True
# 空元组就是False, not inventory 则为True
if not inventory : 
	print("You are empty-handed")

input("\nPress the entry key to continue.")

#创建一个带有一些内容的元组
inventory = ("sword",
			"armor",
			"sheield",
			"healing poting")

# 打印元组
print("\nThe tuple inventory is : ")
print(inventory)

# 尝试修改元组,元组是不可变的,这行代码会报错
# inventory[0] = "battleax"

# 打印元组中的各个元素
for item in inventory :
	print(item)

# 获取元组的长度
print("You have", len(inventory), "items in your possession.")

# 用in测试成员关系
if "healing potion" in inventory :
	print("You will live to fight another day.")

# 使用索引,随机访问元素
# 通过索引显示元素
index = int(input("\nEnter the index number for an item in inventory: "))
print("At index", index, "is", inventory[index])

# 对元组进行切片
start = int(input("\nEnter the index number to begin a slice: "))
finish = int(input("\nEnter the index number to end the slice: "))

print("inventory[", start, ",", finish, "] is", end = " ")
print(inventory[start:finish])

# 连接两个元组
chest = ("gold", "gems")
print("\nYou find a chest. It contains: ")
print(chest)
print("You add the contents of the chest to you inventory.")
inventory += chest
print("Your inventory is now: ")
print(inventory)


input("\n\nPress the enter key to exit.")

理解元组的不可变性

将下面一行代码解注释后程序会报错,因为元组也是不可变序列,修改肯定是不行的。

尝试修改元组,元组是不可变的,这行代码会报错

inventory[0] = "battleax"

相关推荐
^哪来的&永远~15 小时前
Python 轻量级 UI:EEG 与 fNIRS 预处理图形界面
python·可视化·功能连接·eeg·mne·fnirs·eeglab
AI大佬的小弟15 小时前
Python基础(11):Python中函数参数的进阶模式详解
python·lambda函数·函数的参数解释·函数的参数进阶·位置参数·关键词参数·匿名函数与普通函数
智算菩萨15 小时前
Python可以做哪些小游戏——基于Python 3.13最新特性的游戏开发全指南(15万字超长文章,强烈建议收藏阅读)
python·pygame
智航GIS15 小时前
9.1 多线程入门
java·开发语言·python
qq192572302715 小时前
QT的QML
开发语言·qt
nvd1115 小时前
FastMCP 开发指南: 5分钟入门
人工智能·python
情缘晓梦.16 小时前
C语言分支与循环
c语言·开发语言
消失的旧时光-194316 小时前
从 Java 接口到 Dart freezed:一文彻底理解 Dart 的数据模型设计
java·开发语言·flutter·dart
大头流矢16 小时前
C++的类与对象·三部曲:初阶
开发语言·c++