读《Python编程:从入门到实践》
一
1 字符串String
- 引号括起的是字符串,可以是单引号,也可以是双引号,这种灵活性让你能够在字符串中包含引号和撇号:
'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
"One of Python's strengths is its diverse and supportive community."
- 用
+拼接字符串 - 制表符
\t - 换行符
\n strip()删除字符串空格
rstrip()删除字符串尾部空格lstrip()删除字符串头部空格
title()使得字符串第一个字符变大写upper()大写lower()小写
2 数字Number
- int、float、bool、complex(复数)
- 浮点数在小数位会有误差
str()将非字符串转为字符串,可以用来避免类型错误
除法/:2、3大不同
float除法:不截断小数部分
整除法:截断小数部分
- Python2
- 两个int相除,整除法 ,结果为int;
- 否则,float除法,结果为float;
print(3/2)
print(3.0/2)
print(4/2)
print(4.0/2)
# 1
# # 1.5
# # 2
# # 2.0
- Python3
- float除法
- 结果为
float类型
print(3/2)
print(3.0/2)
print(4/2)
print(4.0/2)
# 1.5
# 1.5
# 2.0
# 2.0
除法//:整除法
在Python2和Python3中结果一样。两个int相除结果为int,否则结果为float。
print(3//2)
print(3.0//2)
print(4//2)
print(4.0//2)
# 1
# 1.0
# 2
# 2.0
3 代码原则
漂亮、简单、可读、易懂
二 List
可变对象,可迭代对象
1 增删改查
append(),尾部新增;insert(),插入,指定索引位置;
a = [1, 2, 3]
a.insert(1, "haha")
print(a)
# [1, 'haha', 2, 3]
# 在原List的1号索引的元素前一个位置插入。
del(),删除指定索引位置的元素;
a = [1, 2, 3]
del(a[1])
print(a)
# [1, 3]
pop(),指定索引位置的元素弹出,默认为尾部元素;
a = [1, 2, 3]
end = a.pop()
print(a)
print(end)
# [1, 2]
# 3
a = [1, 2, 3]
end = a.pop(1)
print(a)
print(end)
# [1, 3]
# 2
remove:根据元素值删除元素,仅删除第一个指定的元素;
a = [1, 2, 3, 1]
a.remove(1)
print(a)
# [2, 3, 1]
- 改:
a = [1, 2, 3]
a[1] = 10
print(a)
# [1, 10, 3]
Python编程基础详解
本文深入讲解Python编程的基础知识,包括字符串操作、数字处理、代码规范及列表管理等核心概念。详细介绍了字符串的引用、拼接、格式化及常用操作方法,数字类型及其运算特点,特别是Python2与Python3在除法运算上的区别。同时,文章提供了列表的基本操作,如增删改查及组织技巧,帮助初学者快速掌握Python编程。
1959

被折叠的 条评论
为什么被折叠?



