基本数据类型——数字类型

一、   数字类型:int、float

(一)int类型

1、定义

 int是一种数据类型,在编程语言(c、c++、c#、java等)中,是用于定义整数类型变量的标识符。

在一般的电脑中,int占用4字节(Byte),32个二进制位(bit,二进制数字中的一位

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

除了int类型之外,还有short、long、long long类型可以表示整数,即short int 等 。 unsigned int 表示无符号整数

2、作用 

>>> 
>>> age=input('please input your age:')
please input your age:18
>>> print(int(age)) #强制类型转换,将input输入所得的字符串数据转换为int类型 18
>>> age=int(10.5)
>>> print('age')
age
>>> print(age)
10
>>> #名字(参数)——
>>> int()
>>> print()
>>> input()
''
>>> x=int(2)
>>> name=input('your name:')
your name:cc
>>> res=print('ccc')
ccc
>>> 

 

3、类型转换——

 【2020Python修炼记7】Python语法入门—基本数据类型_数字类型(整型+浮点型) Python

>>> 
>>> #纯数字的字符串转换成int
>>> res=int('100222')
>>> print(res,type(res))
100222 <class 'int'>
>>> 
>>> #了解知识
>>> #数字有不同进制,不同进制数据之间如何转换
>>> #二进制—>十进制
>>> #1011---->8+2+1=11
>>> #十进制—>二进制
>>> # 11----->1011
>>> print(bin(11)) #0b1011 将11转换成二进制 0b1011 >>> #十进制—>八进制 >>> print(oct(11)) 0o13 >>> #十进制—>十六进制 >>> print(hex(11)) 0xb >>> print(hex(123)) 0x7b >>> #其他进制转换成十进制 >>> print(int('0b1011',2)) 11 >>> print(int('0o13',8)) 11 >>> print(int('0xb',16)) 11 >>>

  

(二)float 类型

1、定义

float 类型,用于存储单精度浮点数或双精度浮点数。

float 单精度浮点数在机内占 4 个字节,用 32 位二进制描述。

double 双精度浮点数在机内占 8 个字节,用 64 位二进制描述。

 

参考资料:

https://www.runoob.com/w3cnote/float-and-double-different.html

2、作用

 eg :

salary=3.1     # salary=float(3.1)

3、类型转换 

>>> res=float('3.45')
>>> print(res,type(res))
3.45 <class 'float'>
>>> s=5
>>> res=float(s)
>>> print(res,type(res))
5.0 <class 'float'>
>>> 

4、使用

# int与float没有需要掌握的内置方法
# 他们的使用,就是数学运算+比较运算

 

二、字符串类型 str

1、定义

name = 'Tony'

address = ''上海市浦东新区''

sex = '''男
           喜欢面条'''

 单引号、双引号、多引号,都可以定义字符串,本质上是没有区别的,不过需要注意:

#1、需要考虑引号嵌套的配对问题
msg = "My name is Tony , I'm 18 years old!" 
#内层有单引号,外层就需要用双引号

#2、多引号可以写多行字符串
msg = '''
        天下只有两种人。
比如一串葡萄到手,一种人挑最好的先吃,另一种人把最好的留到最后吃。
        照例第一种人应该乐观,因为他每吃一颗都是吃剩的葡萄里最好的;
第二种人应该悲观,因为他每吃一颗都是吃剩的葡萄里最坏的。
        不过事实却适得其反,缘故是第二种人还有希望,第一种人只有回忆。
      '''

2、作用

  用来记录人的名字,家庭住址,性别等描述性质的状态

3、类型转换

# str可以把任意其他类型都转成字符串
>>> 
>>> res=str({'a':1})
>>> print(res,type(res))
{'a': 1} <class 'str'>
>>> 

 

4、使用:

4.1 数学运算

数字可以进行加减乘除等运算,字符串呢?也可以,但只能进行"相加""相乘"运算。
>>> name = 'tony'
>>> age = '18'
>>> name + age #相加其实就是简单的字符串拼接
'tony18'
>>> name * 5 #相乘就相当于将字符串相加了5次 'tonytonytonytonytony'

 

4.2 内置方法

4.2.1、按索引取值——(正向取+反向取) :只能取

>>> msg='hello world'
>>> #正向取
>>> print(msg[0])
h
>>> print(msg[5])
 
>>> #反向取
>>> print(msg[-1])
d
>>> #只能取,不能改写
>>> msg[0]='H'
Traceback (most recent call last):
  File "<pyshell#86>", line 1, in <module>
    msg[0]='H'
TypeError: 'str' object does not support item assignment
>>> 

 

4.2.2、切片——索引的拓展应用,从一个大字符串中拷贝出一个子字符串

>>> # 顾头不顾尾
# [x:y],--指的是 [x,y)左闭右开的区间
# x--开始的索引号, # y--在索引号[y-1]结束,取到索引号[y-1] 所指的字符就结束 [0:5],意为 从第一个索引[0]所指的字符开始,取到索引[4],即5个字符 >>> >>> msg='hello world' >>> res=msg[0:5] >>> print(res) hello >>> print(msg) hello world >>> >>> #步长 # 依次读取索引 0 2 4 所对应的字符 # [x:y:z], # x--开始的索引号, # y--在索引号[y-1]结束,即取到索引号[y-1] 所指的字符就结束, # z--间隔的索引个数,即从索引[x]开始,每隔z个间隔,依次读取,直到索引号[y-1]结束 [0:5:2],意为 从第一个索引[0]所指的字符开始,每隔2个间隔,读取一个字符,直到取到索引[4],即3个字符 >>> res=msg[0:5:2] >>> print(res) hlo >>>
>>> #反向步长(了解) >>> msg='hello world' >>> res=msg[5:0:-1] >>> print(res) olle >>> >>> msg='hello world' >>> res=msg[:] # [:]不输入,默认为 res=msg[0:11] >>> print(res) hello world >>> res=msg[::-1] # 把字符串倒过来读取 >>> print(res) dlrow olleh >>>

4.2.3、长度 len()

>>> 
>>> msg='hello world'
>>> print(len(msg))
11
>>> 

4.2.4、成员运算in和not in

>>> 
>>> #判断一个子字符串是否存在于一个大字符串中
>>> print("alex" in "alex is sb")
True
>>> print("alex" not in "alex is sb")
False
>>> print(not "alex" in "alex is sb") # 不推荐使用,语法没错,只是不符合一般逻辑思维习惯
False
>>> 

4.2.5、移除字符串左右两侧的符号strip(‘字符’)

           #注意,字符要用引号括起来

>>> 
>>> # 默认去掉的空格
>>> msg='      egon      '
>>> res=msg.strip()
>>> print(msg) # 不会改变原值
      egon      
>>> print(res) # 去除了空格,是产生了新值
egon
>>> 

 

>>> #去掉其他符号
>>> msg='*******egon****'
>>> print(msg.strip('*'))
egon
>>> msg='@@@egon@@*'
>>> print(msg.strip('*'))
@@@egon@@
>>> print(msg.strip('*@'))
egon
>>> 
>>> msg='@@@egon@ @ *'
>>> print(msg.strip('*@ '))
egon
>>> 
>>> # 了解:strip只去除两边,不去中间
>>> msg='*******eg*****on****'
>>> print(msg.strip('*'))
eg*****on
>>> msg='**/*=-**egon**-=()**'
>>> print(msg.strip('*/-=()'))
egon
>>> 
>>> # 应用_自动清除用户手抖输入的多余空格

>>> in_name= input('please input your name:').strip() please input yuor name:' cc' # 为何failed login,原因是这里输入的结果为字符串 ' cc',而不 字符串 cc,后面的条件判断是字符串 cc
>>> in_code= input('please input your code:').strip() please input yuor code:' 123' # 为何failed login,原因是这里输入的结果为字符串 ' 123',而不是 字符串 123,后面的条件判断是字符串 123 >>> if in_name == 'cc'and in_code == '123': print('login successfully') else: print('failed login')


failed login
>>> in_name= input('please input yuor name:').strip()
please input yuor name:cc
>>> in_code= input('please input yuor code:').strip()
please input yuor code:123
>>> if in_name == 'cc' and in_code == '123':
    print('login successfully')
else:
    print('failed login')

    
login successfully
——————————————————————————

>>> in_name= input('please input yuor name:').strip()
please input yuor name:cc
>>> in_code= input('please input yuor code:').strip()
please input yuor code: 123  #末尾有输入一个空格
>>> if in_name == 'cc'and in_code == '123':
    print('login successfully')
else:
    print('failed login')

   
login successfully
———————————————————————————

>>> in_name= input('please input yuor name:').strip() please input yuor name:'cc' # 为何failed login,原因是这里输入的结果为字符串 ' cc',而不 字符串 cc,后面的条件判断是字符串 cc >>> in_code= input('please input yuor code:').strip() please input yuor code:123 >>> >>> if in_name == 'cc'and in_code == '123': print('login successfully') else: print('failed login') failed login ————————————————————————————— >>> in_name= input('please input yuor name:').strip() please input yuor name:cc >>> in_code= input('please input yuor code:').strip() please input yuor code:123 >>> if in_name == 'cc' and in_code == 123: #将123的引号去掉,则为整型。但是用户输入的是字符串类型,所以后面判断结果为假 print('login successfully') else: print('failed login') failed login —————————— >>> in_name= input('please input yuor name:').strip() please input yuor name:cc >>> in_code= input('please input yuor code:').strip() please input yuor code:123
>>> in_code=int(in_code) #用户输入的密码,是字符串类型,将其强制转换为整型,再进行条件判断,则结果为真
>>> if in_name == 'cc'and in_code == 123: print('login successfully') else: print('failed login') login successfully >>>

 

4.2.6、切分split:把一个字符串按照某种分隔符进行切分,得到一个列表
          # # 默认分隔符是空格

>>> # 默认分隔符是空格
>>> info='cat love mili'
>>> res=info.split()
>>> print(res)
['cat', 'love', 'mili']

>>> # 指定分隔符
>>> info='cat:love:mili'
>>> res=info.split(':')
>>> print(res)
['cat', 'love', 'mili']

>>> # 指定分隔次数(了解)
>>> info='cat:love:mili'
>>> res=info.split(':',1)
>>> print(res)
['cat', 'love:mili']
>>> 

4.2.7、循环

>>> 循环输出,即一直循环输出,逐字输出,直到输出完毕
>>> info='cat love mili'
>>> for x in info:
    print(x)

    
c
a
t
 
l
o
v
e
 
m
i
l
i
>>> 

 

4.3 需要掌握的其他应用

4.2.1、strip,lstrip,rstrip

>>> msg='*******egon****'
>>> print(msg.strip('*'))
egon
>>> print(msg.lstrip('*')) #去除left左侧
egon****
>>> print(msg.rstrip('*')) #去除right右侧
*******egon

4.2.2、lower,upper

>>>
>>> msg='AAAAAegondddASSss'
>>> print(msg.lower()) #全部转换成小写
aaaaaegondddassss

>>> print(msg.upper())#全部转换成大写
AAAAAEGONDDDASSSS
>>> 

4.2.3、startswith,endswith——判断字符串的开头或结尾的子字符

>>> 
>>> print('cat love mili'.startswith('cat'))
True
>>> print('cat love mili'.startswith('mili'))
False
>>> print('cat love mili'.endswith('mili'))
True
>>> print('cat love mili'.endswith('cat'))
False
>>> 

4.2.4、format——赋值

>>> #逐一将format后面的值赋给{}
>>> res='{} {} {}'.format('cc','18','mili')
>>> print(res)
cc 18 mili

>>> #按照 format后面的值的索引,赋值给对应索引号的{}
>>> res='{1} {0} {1}'.format('cc','18','mili')
>>> print(res)
18 cc 18
>>> res='{0} {2} {1}'.format('cc','18','mili')
>>> print(res)
cc mili 18

>>> #按照 format后面的变量名称,赋值给对应变量名称的{}
>>> res='{name} {age} {lover}'.format(lover='mili',name='cc',age='18')
>>> print(res)
cc 18 mili
>>> 

4.2.5、split,rsplit:将字符串切成列表

>>> info='cat:love:mili'
>>> print(info.split(':',1))
['cat', 'love:mili']
>>> print(info.rsplit(':',1))#从右侧开始切片
['cat:love', 'mili']
>>> 

4.2.6、join: 把列表拼接成字符串

>>>连接字符串的三种方式:

>>> l=['cat','love','mili']
>>> res=l[0]+":"+l[1]+":"+l[2]
>>> print(res)
cat:love:mili

>>> res=':'.join(l)# 按照某个分隔符号,把元素全为字符串的列表拼接成一个大字符串
>>> print(res)
cat:love:mili

>>> ':'.join(l)
'cat:love:mili'
>>> 

4.2.7、replace

>>> info='cat love mili love cat'
>>> print(info.replace('cat','CC')) #未指定个数,默认将全部'cat'替换为'CC'
CC love mili love CC

>>> info='cat love mili love cat'
>>> print(info.replace('cat','CC',)) #未输入替换个数,默认将全部'cat'替换为'CC'
CC love mili love CC

>>> info='cat love mili love cat'
>>> print(info.replace('cat','CC',1)) #输入替换个数为1,将第一个'cat'替换为'CC'
CC love mili love cat

>>> info='cat love mili love cat'
>>> print(info.replace('cat','CC',2)) #输入替换个数为‘cat’的总数,将全部'cat'替换为'CC'
CC love mili love CC

>>> info='cat love mili love cat'
>>> print(info.replace('cat','CC',3)) #输入替换个数超过‘cat’的总数,将全部'cat'替换为'CC'
CC love mili love CC

4.2.8、isdigit

>>> 
>>> # 判断字符串是否由纯数字组成
>>> print('123'.isdigit())
True
>>> print('12.3'.isdigit())
False
>>> 
>>>
>>> age=input('请输入你的年龄:').strip()
请输入你的年龄:19
>>> if age.isdigit():
    age=int(age)
    if age > 18:
        print('猜大了')
    elif age < 18:
        print('猜小了')
    else:
        print('猜对了')
else:
    print('请输入数字')

    
猜大了
>>> 

4.4 其他应用的了解

4.4.1、find,rfind,index,rindex,count

# msg='hello egon hahaha'
# 找到返回起始索引
# print(msg.find('e')) # 返回要查找的字符串在大字符串中的起始索引
# print(msg.find('egon'))
# print(msg.index('e'))
# print(msg.index('egon'))
# 找不到
# print(msg.find('xxx')) # 返回-1,代表找不到
# print(msg.index('xxx')) # 抛出异常

# msg='hello egon hahaha egon、 egon'
# print(msg.count('egon'))

4.4.2、center,ljust,rjust,zfill

# print('egon'.center(50,'*'))
# print('egon'.ljust(50,'*'))
# print('egon'.rjust(50,'*'))
# print('egon'.zfill(10))

4.4.3、expandtabs

# msg='hello\tworld'
# print(msg.expandtabs(2)) # 设置制表符代表的空格数为2

4.4.4、captalize,swapcase,title

# print("hello world egon".capitalize())
# print("Hello WorLd EGon".swapcase())
# print("hello world egon".title())

4.4.5、is数字系列

4.4.6、is其他

# print('abc'.islower())
# print('ABC'.isupper())
# print('Hello World'.istitle())
# print('123123aadsf'.isalnum()) # 字符串由字母或数字组成结果为True
# print('ad'.isalpha()) # 字符串由由字母组成结果为True
# print('     '.isspace()) # 字符串由空格组成结果为True
# print('print'.isidentifier())
# print('age_of_egon'.isidentifier())
# print('1age_of_egon'.isidentifier())


num1=b'4' #bytes
num2=u'4' #unicode,python3中无需加u就是unicode
num3='' #中文数字
num4='' #罗马数字

# isdigit只能识别:num1、num2
# print(num1.isdigit()) # True
# print(num2.isdigit()) # True
# print(num3.isdigit()) # False
# print(num4.isdigit()) # False



# isnumberic可以识别:num2、num3、num4
# print(num2.isnumeric()) # True
# print(num3.isnumeric()) # True
# print(num4.isnumeric()) # True

# isdecimal只能识别:num2
print(num2.isdecimal()) # True
print(num3.isdecimal()) # False
print(num4.isdecimal()) # False

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄