本文将从多个方面对Python中常用的小知识点进行详细的阐述。
一、字符串处理
1、字符串长度
s = "Hello, world!"
print(len(s)) # 输出:13
2、字符串拼接
s1 = "Hello"
s2 = "world"
sentence = s1 + " " + s2
print(sentence) # 输出:Hello world
3、字符串索引和切片
s = "Hello, world!"
print(s[0]) # 输出:H
print(s[7:12]) # 输出:world
二、列表操作
1、列表长度
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # 输出:5
2、列表追加元素
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # 输出:[1, 2, 3, 4]
3、列表切片
my_list = [1, 2, 3, 4, 5]
print(my_list[1:3]) # 输出:[2, 3]
三、条件控制
1、if语句
x = 10
if x > 5:
print("x is greater than 5")
2、if-else语句
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
3、if-elif-else语句
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
四、循环
1、for循环
for i in range(5):
print(i)
2、while循环
i = 0
while i < 5:
print(i)
i += 1
3、循环控制语句
for i in range(10):
if i == 5:
break
print(i)
五、函数定义与调用
1、函数定义
def say_hello(name):
print("Hello, " + name + "!")
2、函数调用
say_hello("Alice")
3、函数返回值
def add(x, y):
return x + y
result = add(3, 5)
print(result) # 输出:8
六、文件操作
1、读取文件内容
with open("file.txt", "r") as file:
content = file.read()
print(content)
2、写入文件内容
with open("file.txt", "w") as file:
file.write("Hello, world!")
3、文件追加内容
with open("file.txt", "a") as file:
file.write("Hello again!")
以上是Python中常用的一些小知识点的详细阐述,希望能对你有所帮助。
原创文章,作者:NPYH,如若转载,请注明出处:https://www.beidandianzhu.com/g/7873.html