Python 001 字符串 str 列表 list 操作合集


一、字符串 str 操作合集

二、列表 list 操作合集



1. python 查看变量类型 type()

print(type(2))
<class 'int'>

print(type(2.0))
<class 'float'>

print(type(2.111111))
<class 'float'>


2. python 科学计数法

# ,e-08表示的是10的-8次方
print(9.8 ** -7.2)
7.297468937055047e-08

# 2e3 表示2* 10的3次方
print(2e3)
2000.0


3. python 取余数

print(5 % 2)  # 1

print(5.0 % 2)  # 1.0


4. python 四舍五入 round()

round(1.234567, 2)  # 1.23

print(5.0 % 2)  # 1.0


5. python math

math 是标准库之一,所以不用安装,可以直接使用。使用方法是:

import math

print(math.pi)  # 3.141592653589793

print(math.sqrt(9))  # 3.0

print(math.floor(3.14))  # 3

print(math.floor(3.92))  # 3


# #等价于abs(-2)
print(math.fabs(-2))  # 2.0

#等价于5%3
print(math.fmod(5.3))  # 2.0

print(dir(math))

help(math.pow)


['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan 2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isi nf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radian s', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

dir(module) 是一个非常有用的指令,可以通过它查看任何模块中所包含的工具。从上面的列 表中就可以看出,在math模块中,可以计算正sin(a),cos(a),sqrt(a)…

help() 是好帮手。y用来来查看每个函数(方法)的使用方法。



6. 字符串引号问题

# 解决方法一:双引号包裹单引号
print("What's your name?")
"What's your name?"
#  解决方法二:使用转义符
print('What\'s your name?')
"What's your name?"
#  三个 单引号 或者双引号 可以解决换行
print("""What\'s your name? 
 my name is libin""")
 
# 输出结果为
What's your name? 
my name is libin


7. python 连接字符串

# 1.直接相加
print("py" + "thon")  # "python"

a = 1989
b = "free"
# print(b + a) 这种会报错 TypeError: unsupported operand type(s) for +: 'int' and 'str' 。
print(b + str(a))  # "free1989"

# repr()是一个函数,其实就是反引号的替代品
print(b + repr(a))  # "free1989"


8. python 字符串换行

print("I like \npython")
I like 
python


9. python 转译字符

转义字符描述
\\ (在行尾时) 续行符
\\ 反斜杠符号
\’单引号
\"双引号
\a响铃符
\b退格(Backspace)
\e转义
\000
\n换行
\v纵向制表符
\t横向制表符
\r回车
\f换页
\oyy八进制数,yy代表的字符,例如:\o12代表换行
\xyy十六进制数,yy代表的字符,例如:\x0a代表换行
\other其它的字符以普通格式输出


10. python 输入

 name = input("input your name:") #Python 3 input your name:python
 # 等待用户输入后 
 print(name)


11. python 字符串 索引和切片

lang = "study python # 等待用户输入后 
print(lang[0])  # "s"


# 要得到多个字符 前包括,后不包括
print(lang[2:9])  # 'udy pyt'

# 从1号到最末尾的字符
print(lang[1:])  # 'tudy python'

# 从第一个到10号之前的字符
print(lang[:10])  # 'study pyth'

# 在获取切片的时候,如果冒号的:
# 前面不写数字,就表示从字符串的第一个开始(包括第一个);
# 后面的序号不写,就表示到字符串的到最末一个字符结束(包括最后一个)。

# index 获取索引
lang.index("p")

# 字符串基本操作
# len():求序列长度,会计算空格和标点
print(len("python"))  # 6

# in :判断元素是否存在于序列中
print("p" in "python")  # True

# max() :返回最大值; min() :返回最小值
print(max("python"))  # "y"

print(min("python"))  # "h"

# 打印一个华丽的分割线
print("-" * 20)  # --------------------



12. python format() 格式化输出

{} 表示占位符
{0:10} 表示第一个位置,有10个字符那么长
{1:>15} 表示第二个位置,有15个字符那么长,并且放在这个位置的字符是右对齐
^ 表示居中对齐

# string.format()
print("I like {0} and {1}".format("python", "canglaoshi"))
'I like python and canglaoshi'

#  {0:10} 表示第一个位置,有10个字符那么长
#  {1:>15} 表示第二个位置,有15个字符那么长,并且放在这个位置的字符是右对齐
print("I like {0:10} and {1:>15}".format("python", "canglaoshi"))
"I like python     and      canglaoshi"

# 现在是居中对齐了
print("I like {0:^10} and {1:^15}".format("python", "canglaoshi"))
"I like   python   and   canglaoshi   "


#  {0:.2} : 0 说明是第一个位置,对应传入的第一个字符串。
# .2 表示对于传入的字符串, 截取前两个,并放到第一个位置,
# 注意的是,在 : 后面和 . 号前面,没有任何数字,意思是 该位置的长度自动适应即将放到该位置的字符串。

# {1:^10.4} : 1 说明是第二个位置,对应传入的第二个字符串。
#  ^ 表示放到该位置的字符串 要居中;
# 10 表示该位置的长度是10个字符串那么长,
# .4 即将放入该位置的字符串应该仅 仅有4个字符那么长,要截取前四个字符,即 为 "cang" 。
print("I like {0:.2} and {1:^10.4}".format("python", "canglaoshi"))
"I like py and    cang   "


# 还可以传入数字(包括整数和浮点数)
# {0:d} 表示在第一个位置放一个整数;
#  {1:f} 表示在第二个位置放一个浮点数,浮点数小数位数是默认的
print("She is {0:d} years old and the breast is {1:f}cm".format(28, 90.1415926))
'She is 28 years old and the breast is 90.141593cm'

# {0:4d} 表示第一个位置的长度是4个字符,并且默认状态下是右对齐。
# {1:6.2f} 表示第二个位置的长度使6个字符,并且填充到该位置的浮点数要保留两位小数, 默认也是右对齐。
print("She is {0:4d} years old and the breast is {1:6.2f}cm".format(28, 90.1415926))
'She is   28 years old and the breast is 90.14cm'

# {0:04d} 和 {1:06.2f} 在声明位置长度的数字前面多了 0 ,其含义是在数字前面,如果位数不足,则补 0 。
print("She is {0:04d} years old and the breast is {1:06.2f}cm".format(28, 90.1415926))
'She is 0028 years old and the breast is 090.14cm'


# key  一一对应
print( "I like {lang} and {name}".format(lang="python", name="canglaoshi"))
'I like python and canglaoshi'

# key 比较多的时候 可以提出来
data = {"name":"Canglaoshi", "age":28}
print("{name} is {age}".format(**data))
'Canglaoshi is 28'


13. python 字符串常用方法

S.isalpha() 字符串全是字母,返回 bool 类型
S.strip() :去掉字符串的左右空格
S.lstrip() :去掉字符串的左边空格
S.rstrip() :去掉字符串的右边空格

S.upper() :S中的字母大写
S.lower() :S中的字母小写
S.capitalize() :首字母大写
S.isupper() :S中的字母是否全是大写
S.islower() :S中的字母是否全是小写
S.istitle() :S中字符串中所有的单词拼写首字母是否为大写,且其他字母为小写(标题都这么写)

S.join(a) 拼接字符串

c = ['www', 'itdiffer', 'com']
print(".".join(c))  # www.itdiffer.com

split() 是将字符串根据某个分割符进行分割

# 是用空格作为分割,得到了一个名字叫做列表(list)的返回值
a = "I LOVE PYTHON"
prtint(a.split(" ")) # ['I', 'LOVE', 'PYTHON']


14. python 获取字符编码

import sys
print (sys.getdefaultencoding())  # 'utf-8'


15. python 获取保留关键字

import sys
print (sys.getdefaultencoding())  # 'utf-8'
# 编码
str.encode()


16. python 字符串转列表 str 转 list ,字符串拆分成列表

第一个参数:指定分割字符,默认值为 " "
第二个参数,指定分割次数

stra = "I am abc Welcome you"
print(stra.split())  # ['I', 'am', 'abc', 'Welcome', 'you']


# stra.split(" ", 1)
print(stra.split(" ", 1))  # ['I', 'am abc Welcome you']






二、列表 list 操作合集

1. python list 索引和切片

a = ['2', 3, 'qiwsir.github.io']
print(a[0])  # '2'
print(a[:2])  # ['2', 3]
print(a[1:])  # [3, 'qiwsir.github.io']
# 二次切片
print(a[2][7:13])  # 'github'


# list 和 str 类似
lang = "python"
lang.index("y")  # 1

lst = ['python','java','c++']
lst.index('java')  # 1

# 从右边开始取
lang[-1]  # 'n'
lst[-1]  # 'c++'

# 从右边开始切片要注意 序列的切片,一定要左边的数字小于右边的数字
lang[-1:-3]  # '' 这是错误的写法

lang[-3:-1]  # 'ho'
lst[-3:-1]  # ['python', 'java']


2. python 反转 新生成了一个值



lang = 'python'
print(lang[::-1])  # 'nohtyp'
print(list(reversed(lang )))  # ["n", "o", "h", "t", "y", "p"]

print(lang)  # 'python'

alst = [1, 2, 3, 4, 5, 6]
print(alst[: : -1])  # [6, 5, 4, 3, 2, 1]
print(alst)  # [1, 2, 3, 4, 5, 6]
print(list(reversed(alst)))  # [1, 2, 3, 4, 5, 6]

和 str 类似 有以下方法
len()
in()
max()
min()



3. python list 追加元素 append() 会改变原始数据,没有返回值

a = ["good", "python", "I"]
a.append("like")
print(a)  # ['good', 'python', 'I', 'like']
a.append(100)
print(a)  # ['good', 'python', 'I', 'like', 100]

# 两种方法都可以
a[len(a):]=[3] #len(a),即得到列表的长度
print(a)  # ['good', 'python', 'I', 'like', 100, 3]


4. python list 合并 extend() 会改变原始数据,没有返回值

la = [1, 2, 3]
lb = ['qiwsir', 'python']
la.extend(lb)
print(la)  # [1, 2, 3, 'qiwsir', 'python']
print(lb)  # ['qiwsir', 'python']
la = [1, 2, 3]
b = "abc"
# list 可以 合并 str  但是会把 str 拆开
la.extend(b)
print(la)  # [1, 2, 3, 'a', 'b', 'c']

c = 5
la.extend(c)
print(la)  # 报错 'int' object is not iterable

同上,第二种写法

la = [1, 2, 3, 'a', 'b', 'c']
lb = ['qiwsir', 'python']
la[len(la):]=lb
print(la)  # [1, 2, 3, 'a', 'b', 'c', 'qiwsir', 'python']

count() 是一个帮着我们弄清楚列表中元素重复出现次数的方法

la = [1, 2, 1, 1, 3, 'a', 'a']
la.count(1)  # 3
la.count('a')  # 2 
# la中没有5,但是如果用这种方法找,不报错,返回的是数字0
la.count(5) # 0


5. python list 插入元素 insert() 会改变原始数据,没有返回值

与 list.append(x) 类似, list.insert(i,x) 也是对list元素的增加。只不过是可以在任何位置增加一个元素。
最好不要用 list 作为变量名字,因为它是Python 中内置的对象类型的名字

la = ['qiwsir', 'github', 'io']
# list.insert(i, x)  i 是将元素 x 插入到列表中的位置 从0 开始
la.insert(0,"algorithm")
print(la)  # ['algorithm',qiwsir', 'github', 'io']

# ,如果遇到那个 i 已经超过了最大索引值,会自动将所要插入的元素放到列表的尾 部,即


6. python list 删除制定元素 remove() 会改变原始数据,没有返回值

la = ['qiwsir', 'github', 'io']
# list.remove(x)  如果x没有在list中,会报错。
la.remove('github')
print(la)  # ['qiwsir', 'io']


7. python list 删除制定元素 pop() 会改变原始数据,返回被删除元素

la = ['qiwsir', 'github', 'io']
# list.pop([i])  默认删除最后一个  i超出索引返回也会报错
print(la.pop()) # "io"
print(la)  # ['qiwsir', 'github']


8. python list 排序 sort() 会改变原始数据,没有返回值

la =  [6, 1, 5, 3]
la.sort()
print(la)  # [1, 3, 5, 6]

# 从大到小排序
a.sort(reverse=True)
print(la)  # [6, 5, 3, 1]

# 按元素长度排序
lst = ["python","java","c","pascal","basic"]
lst.sort(key=len)
print(lst)  # ['c', 'java', 'basic', 'python', 'pascal']


python 预留关键字

# 查询哪些是保留字,给变量取名的时候避开
import keyword
keyword.kwlist
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值