python中numstr_python02-basic-num-str

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  = 1a1type(a)int

name = value

命名规则.不能使用中文.大小写.有意义的单词.不与关键词重复.连接符.全大写一般作为全局变量number = 3 num = 4number3num4name = "coop"name'coop'type(name)strtype(num)intresult = 1 + 4result5

数字.why 计算 日常数字 游戏 图像. what .how :对比py2# 数学计算3 + 583-3.5-0.53-3.345-0.34500000000000023*5153*t---------------------------------------------------------------------------NameError                                 Traceback (most recent call last) in ()----> 1 3*tNameError: name 't' is not defined3*'t''ttt'#取整数3//503 % 53type(2.5)floattype(4)intnumber = 111_222_333# 一样是表示数字number111222333type(True)booltype(False)bool

内置类型,内置函数和标准库import randomrandom.randint(2,9) # 返回2和9之间的随机整数2import randomrandom.choice?round(3.4)3import mathmath.floor(3.6)  # 取小3math.ceil(3.2) #取大4math.pi3.141592653589793math.pow(3,2)  # 默认是小数9.0math.sin(30)-0.9880316240928618math.hypot(3,4)  # 勾股定理5.0math.sin(30)-0.9880316240928618math.exp(3)---------------------------------------------------------------------------NameError                                 Traceback (most recent call last) in ()----> 1 math.exp(3)NameError: name 'math' is not definedimport 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']]

列表的插入:insertmy_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]123my_list[-1]6my_list[-2]-1len(my_list)  # 列表长度9my_list.count(123)  # 计算某个元素出现的次数2my_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 importantf'{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)10email.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()Falsepy = 'python is cool'py.index('is')7py.index('o')  # 指定字符的位置4py.find('is')7py.find('asldhfk')-1dir(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:cooplen(name)7type(name)strlen(name.strip())4py = 'python2 python3 python4 python8'py[3]'h'py[-1]'8'py[:6]'python'py.index('2')6py[:py.index('2')]  #切片的嵌套操作'python'something = 'abcdefg1234567'something[1:6:3]'be'something[:4]'abcd'something[4:]'efg1234567'something[4::4]  # 步长就是第n个,隔n-1个'e26'

somethingsomething.index('e')4email'123#qq.com'email.split('#')  # 以#号为分隔符,生成一个列表['123', 'qq.com']email.index('#')  # 少用,建议用find3email[: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)intnum = 'coop'num.isdigit()Falsenum.isalpha()Truenumber = '三'number.isdigit()Falsenumber.isalpha()Truenumber =  '3'number.isdecimal()Truenumber.isnumeric()Truenumber.isdigit()Truetype(number)strnumber'3'number.isdigit()True

判断数字范围

isnumeric(能数数的)> isdigit(数字)>isdecimal(十进制)num = 'coop007'num.isalpha()  # 判断是否是字母Falsenum.isnumeric()  # 判断是否是数字Falsetype(num)strnum = input('give me a number:')give me a number:1213num'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=1for j in range(8,0,-1):    for i in range(1,j):        print(i,end='')    print()1234567123456123451234123121for 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= 1for 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=81for 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=1ch_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) in ()      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 randomrandom?  # modulerandom.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) in ()----> 1 s.join(str_list)TypeError: sequence item 5: expected str instance, int foundstr_list1 = ['a','b','c','d','e','1','2']s = ' 's.join(str_list1)  # join方法之针对字符串,对数字无效'a b c d e 1 2'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值