为了账号安全,请及时绑定邮箱和手机立即绑定

python02-basic-num-str

标签:
Python

dir?
dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
dir(int)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

变量

a  = 1
a
1
type(a)
int

name = value

命名规则

.不能使用中文.大小写.有意义的单词.不与关键词重复.连接符.全大写一般作为全局变量
number = 3 num = 4
number
3
num
4
name = "coop"
name
'coop'
type(name)
str
type(num)
int
result = 1 + 4
result
5

数字

.why 计算 日常数字 游戏 图像. what .how :对比py2
# 数学计算3 + 5
8
3-3.5
-0.5
3-3.345
-0.3450000000000002
3*5
15
3*t
---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-50-5341660d56fc> in <module>()----> 1 3*tNameError: name 't' is not defined
3*'t'
'ttt'
 #取整数3//5
0
3 % 5
3
type(2.5)
float
type(4)
int
number = 111_222_333# 一样是表示数字
number
111222333
type(True)
bool
type(False)
bool

内置类型,内置函数和标准库

import randomrandom.randint(2,9) # 返回2和9之间的随机整数
2
import randomrandom.choice?
round(3.4)
3
import mathmath.floor(3.6)  # 取小
3
math.ceil(3.2) #取大
4
math.pi
3.141592653589793
math.pow(3,2)  # 默认是小数
9.0
math.sin(30)
-0.9880316240928618
math.hypot(3,4)  # 勾股定理
5.0
math.sin(30)
-0.9880316240928618
math.exp(3)
---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-5-0e9f30b02870> in <module>()----> 1 math.exp(3)NameError: name 'math' is not defined
import mathmath.log2(8)
3.0

name = input('name:')

name = input("name:")
name:
name
''

新建

"""asdfaadfadsf # 三引号可以换行"""
'\nasdfa\nadf\nadsf # 可以换行\n'
"第一行\第二行\第三行"  # 右斜线也可以用来换行
'第一行第二行第三行'

基本数据结构list

kv:list -> what why how

数据类型->

.增

.删

.改

.查

type([])
list
# 创建 增加my_list = [1,2,3,4,5,6]
my_list
[1, 2, 3, 4, 5, 6]
my_list2 = list([1,2,3,4,5]) # 与上面的等价
my_list2
[1, 2, 3, 4, 5]
my_list3 = list((1,2,3,4))
my_list3
[1, 2, 3, 4]
multi_list = ['coop',2018,'1.2',True]
multi_list  # 不建议使用,列表中一般都是同一类型的数据
['coop', 2018, '1.2', True]
more_list = [1,2,3,4,[5,6,7],9,10]
more_list
[1, 2, 3, 4, [5, 6, 7], 9, 10]
arr = [[1,2,3],[4,5,6],[7,8,9]]  # 矩阵
arr
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
str_list = []  # 列表名称,数据为字符串
str_list
[]
str_list.append('abc')  # 可以在.之后单击tab键,可以显示都有哪些方法
str_list
['abc', 'abc', 'abc', 'abc']
str_list = ['c'*3]  # 列表的增加
str_list
['ccc']
str_list = [['c']*3]  # 列表的增加
str_list
[['c', 'c', 'c']]

列表的插入:insert

my_list
[1, 123, 123, 2, 3, 4, 5, 6]
my_list.insert(-1,-1)
my_list
[1, 123, 123, 2, 3, 4, 5, -1, 6]
my_list.insert?

my_list # 切片 [开始:结束 :步长]
[1, 123, 123, 2, 3, 4, 5, -1, 6]
my_list[1]
123
my_list[-1]
6
my_list[-2]
-1
len(my_list)  # 列表长度
9
my_list.count(123)  # 计算某个元素出现的次数
2
my_list[:3]
[1, 123, 123]
my_list[3:]
[2, 3, 4, 5, -1, 6]
my_list
[1, 123, 123, 2, 3, 4, 5, -1, 6]
my_list[1::2]
[123, 2, 4, -1]
names = ['coop','xxx','world','murphy']
names
['coop', 'xxx', 'world', 'murphy']
names[3]
'murphy'
names.index('world')
2

names
['coop', 'xxx', 'world', 'murphy']
names[2] = 'china'
names
['coop', 'xxx', 'china', 'murphy']
names[-1]  = 'zhao'
names
['coop', 'xxx', 'china', 'zhao']
names.reverse() # 反转数据,会将列表修改
names
['zhao', 'china', 'xxx', 'coop']
names[::-1]
['coop', 'xxx', 'china', 'zhao']
names
['zhao', 'china', 'xxx', 'coop']

删除

names
['zhao', 'china', 'xxx', 'coop']
names.pop(1)
'xxx'
names
['zhao', 'coop']
names
['zhao', 'coop']
names = []  # 删除整个列表
names
[]

字符串的增加

'coop'*5
'coopcoopcoopcoopcoop'
"cop "*5
'cop cop cop cop cop '
# 直接加name = 'coop'city = 'beijing'info = name +' '+ cityinfo
'coop beijing'
# % c style'name:%s,city:%s' %(name,city)  #ctrl +左右箭头  ctrl+shift +左右箭头#字符串里面加%s,表示占位符,后面%跟()表示变量
'name:coop,city:beijing'
# {} format'name:{},city:{}' .format(name,city)
'name:coop,city:beijing'
'name:{},city:{}' .format(city,name)
'name:beijing,city:coop'
'name:{name123},city:{city123}'.format(name123=name,city123=city)#第一个name表示字符串,name123表示增加的变量.format里面的name表示变量,即coop"""
'name:coop,city:beijing'
# f-string  f'{}' 拼接字符串very important
f'{name}:{city}'
'coop:beijing'
f"my name is {name} and i'm in {city}"
"my name is coop and i'm in beijing"

删除字符串

name = 'coop'
name
'coop'
name = ''
name
''

字符串各种修改

name = 'coop'
name.upper()
'COOP'
name
'coop'
name = 'ABCDEFG'
name
'ABCDEFG'
name.lower()
'abcdefg'
names = name.lower()
names
'abcdefg'
name
'ABCDEFG'
names
'abcdefg'
names.capitalize()
'Abcdefg'
name = 'python is cool'
name.title()
'Python Is Cool'
name.strip('python')  # 去除给定开头和结尾的字符串,或者去除字符串两端的空格
' is cool'
name.strip()
'python is cool'
email = '123#qq.com'  # replace 替换指定的字符串
email.replace('#','@')
'123@qq.com'
len(email)
10
email.zfill(15)  # 左边补0,凑齐15个字符串,小于字符串长度的话,不添加0
'00000123#qq.com'
email.zfill(5)
'123#qq.com'
email.ljust(15)  # 用于格式化输出,括号里面指定它的宽度,不够的可以是空格不全,也可以是其他的补全
'123#qq.com     '
email.ljust(15,'$')
'123#qq.com$$$$$'
email.center(15,'*')
'***123#qq.com**'
name
'python is cool'
name.isupper()
False
py = 'python is cool'
py.index('is')
7
py.index('o')  # 指定字符的位置
4
py.find('is')
7
py.find('asldhfk')
-1
dir(py)jjjjkk
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
name = input('name:')
name:coop
len(name)
7
type(name)
str
len(name.strip())
4
py = 'python2 python3 python4 python8'
py[3]
'h'
py[-1]
'8'
py[:6]
'python'
py.index('2')
6
py[:py.index('2')]  #切片的嵌套操作
'python'
something = 'abcdefg1234567'
something[1:6:3]
'be'
something[:4]
'abcd'
something[4:]
'efg1234567'
something[4::4]  # 步长就是第n个,隔n-1个
'e26'

something

something.index('e')
4
email
'123#qq.com'
email.split('#')  # 以#号为分隔符,生成一个列表
['123', 'qq.com']
email.index('#')  # 少用,建议用find
3
email[:email.index('#')]
'123'
email.split("#")[0]
'123'
email[:email.find('#')]
'123'
email[email.find('#'):]
'#qq.com'
email[email.find('#')+1:]
'qq.com'
email.find('@')
-1

数字和字符串的判断

type(8)
int
num = 'coop'
num.isdigit()
False
num.isalpha()
True
number = '三'
number.isdigit()
False
number.isalpha()
True
number =  '3'
number.isdecimal()
True
number.isnumeric()
True
number.isdigit()
True
type(number)
str
number
'3'
number.isdigit()
True

判断数字范围

isnumeric(能数数的)> isdigit(数字)>isdecimal(十进制)

num = 'coop007'
num.isalpha()  # 判断是否是字母
False
num.isnumeric()  # 判断是否是数字
False
type(num)
str
num = input('give me a number:')
give me a number:1213
num
'1213'
num.isdigit()
True

学习要点:

- 逗号,引号,中英文切换

- 字符串 数字转换

- 列表

- 重复的事情交给电脑

- range

- for

- print格式化输出

for i in range(9,0,-1):   # 减号表示反向排列,数字1 表示步长,因为默认是从0开始,现在是从9到0,所以应该加个减号,表示反向。    for j in range(1,i+1):        print(f'{j}*{i}={i*j}',end=" ")    print()
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 1*4=4 2*4=8 3*4=12 4*4=16 1*3=3 2*3=6 3*3=9 1*2=2 2*2=4 1*1=1
for j in range(8,0,-1):    for i in range(1,j):        print(i,end='')    print()
1234567123456123451234123121
for i in range(9,0,-1):   #控制行数    for j in range(1,i+1):   #控制列数        print(f'{j}*{i}={i*j:2}',end=' ')  #控制打印输出,f'{j}*{i}={i*j:2}'中的2表示控制输出的位数    print()
1*9= 9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 1*8= 8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 1*7= 7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 1*6= 6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 1*5= 5 2*5=10 3*5=15 4*5=20 5*5=25 1*4= 4 2*4= 8 3*4=12 4*4=16 1*3= 3 2*3= 6 3*3= 9 1*2= 2 2*2= 4 1*1= 1
for i in range(1,10):    for j in range(1,i+1):        print(f'{i}*{j}={i*j:2}',end=" ")    print()
1*1= 1 2*1= 2 2*2= 4 3*1= 3 3*2= 6 3*3= 9 4*1= 4 4*2= 8 4*3=12 4*4=16 5*1= 5 5*2=10 5*3=15 5*4=20 5*5=25 6*1= 6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1= 7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1= 8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 9*1= 9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
for i in range(9,0,-1):    for j in range(1,i+1):        print(f'{j}*{i}={str(j*i).ljust(2)}',end=' ')  #ljust是列表的方法,所以先使用str将数字改为列表。    print()
1*9=9  2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 1*8=8  2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 1*7=7  2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 1*6=6  2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 1*5=5  2*5=10 3*5=15 4*5=20 5*5=25 1*4=4  2*4=8  3*4=12 4*4=16 1*3=3  2*3=6  3*3=9  1*2=2  2*2=4  1*1=1
ch_numbers = ['','一','二','三','四','五','六','七','八','九','零']numbers = ['','1','2','3','4','5','6','7','8','9','0']for i in range(9,0,-1):    for j in range(1,i+1):        result = str(i*j).ljust(2)        left = ch_numbers[numbers.index(result[0])]        right = ch_numbers[numbers.index(result[0])]        print(f'{ch_numbers[j]}*{ch_numbers[i]}={left}{right}',end=' ')    print()
一*九=九九 二*九=一一 三*九=二二 四*九=三三 五*九=四四 六*九=五五 七*九=六六 八*九=七七 九*九=八八 一*八=八八 二*八=一一 三*八=二二 四*八=三三 五*八=四四 六*八=四四 七*八=五五 八*八=六六 一*七=七七 二*七=一一 三*七=二二 四*七=二二 五*七=三三 六*七=四四 七*七=四四 一*六=六六 二*六=一一 三*六=一一 四*六=二二 五*六=三三 六*六=三三 一*五=五五 二*五=一一 三*五=一一 四*五=二二 五*五=二二 一*四=四四 二*四=八八 三*四=一一 四*四=一一 一*三=三三 二*三=六六 三*三=九九 一*二=二二 二*二=四四 一*一=一一
ch_numbers = ['','一','二','三','四','五','六','七','八','九','零']numbers = ['','1','2','3','4','5','6','7','8','9','0']for i in range(9,0,-1):    for j in range(1,i+1):        result = str(i*j).ljust(2)        left = ch_numbers[result[0]]        right = ch_numbers[numbers.index(result[0])]        print(f'{ch_numbers[j]}*{ch_numbers[i]}={left}{right}',end=' ')    print()
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-418-f42a2d6a2613> in <module>()      4     for j in range(1,i+1):      5         result = str(i*j).ljust(2)----> 6         left = ch_numbers[result[0]]      7         right = ch_numbers[numbers.index(result[0])]      8         print(f'{ch_numbers[j]}*{ch_numbers[i]}={left}{right}',end=' ')TypeError: list indices must be integers or slices, not str

token生成器

用途

- url

- passport

- file name

学习要点:

- random

- string

-字符串与数字综合练习

- 列表

import random
random?  # module
random.choice('asldfhaosdhoasf')
'f'

random.choice?  # Choose a random element from a non-empty sequence.

str_list = ['a','b','c','d','e',1,2]
s = ''
s.join(str_list)
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-429-153df814400f> in <module>()----> 1 s.join(str_list)TypeError: sequence item 5: expected str instance, int found
str_list1 = ['a','b','c','d','e','1','2']
s = ' '
s.join(str_list1)  # join方法之针对字符串,对数字无效
'a b c d e 1 2'

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消