Python-数据类型学习总结

变量

  • 变量名第一个字符必须是字母表中字母或下划线 _ 。
  • 变量名其他的部分由字母、数字和下划线组成。
  • 变量名对大小写敏感。
    Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。
>>> a=1
>>> id(a)    
9322464
>>> id(1)
9322464
>>> c=b=a
>>> id(c)
9322464
>>> id(b)
9322464
#变量a、b、c并没有地址,而是在使用后使用了1的同一地址

python基本内置数据类型

数字类

  1. 整型(Int) - 通常被称为是整型或整数,是正或负整数,不带小数点。Python3 整型是没有限制大小的,可以当作 Long 类型使用,所以 Python3 没有 Python2 的 Long 类型。
>>> a=1
>>> a
1
>>> type(a)				#检测数据类型
<class 'int'>
  1. 浮点型(float) - 浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250)
>>> b=1.34
>>> b
1.34
>>> type(b)
<class 'float'>
  1. 布尔型(bool)-布尔类型只有True和False两种值,0或空表示False,非0或者非空表示True,(非0即真)
>>> a = 1
>>> bool(a)
True
>>> bool(0)
False
>>> bool('')	#此处为空,空为False
False
>>> bool(' ')	#此处不为空,是空格
True
>>> bool('redhat')
True
  1. 复数( (complex)) - 复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示,复数的实部a和虚部b都可以是浮点型,另外虚部可以使用j或者J表示
>>> c=complex(1,3)
>>> c
(1+3j)
>>> type(c)
<class 'complex'>
>>> d=1+4J
>>> d
(1+4j)
>>> type(d)
<class 'complex'>

字符串

字符串定义

  1. 可以用单引号 (’…’) 或双引号 ("…") 标识
  2. 单引号 (’…’) 中,若有需要单引号需要显示,需要 \ 来转义引号
>>> c = "test"
>>> type(c)
<class 'str'>
>>> c = 'test'
>>> type(c)
<class 'str'>
>>> c = 'what\'s'
>>> c
"what's"
>>> c = "what's"
>>> c
"what's"

字符串特性

索引

索引用于获得单个字符

str = 'helloworld'
print(s[0])		# 第一个字符
print(s[4])		# 第四个字符
print(s[-1])	# 最后一个字符
print(str[-2])	# 倒数二个字符
结果:
h
o
d
l
切片

原字符串中获得一个子字符串

#str[start:end:step] 
str = 'helloworld'
print(str)          # 输出字符串
print(str[:])       # 显示所有字符
print(str[0:-1])    # 输出第一个到倒数第二个的所有字符
print(str[0])       # 输出字符串第一个字符
print(str[2:5])     # 输出从第三个开始到第五个的字符
print(str[2:])      # 输出从第三个开始的后的所有字符
print(str[0:3])     # 输出前3个字符
print(str[:3])      # 输出前3个字符
print(str[0:4:2])   # 输出第一个字符和第三个字符
print(str[::-1])    # 字符串的反转
结果:
helloworld
helloworld
helloworl
h
llo
lloworld
hel
hel
hl
dlrowolleh
重复
str = 'helloworld'
print(str * 2)
结果:
helloworldhelloworld
连接
str = 'helloworld'
print(str+'nice day!')
结果:
helloworldnice day!
成员操作符
str = 'helloworld'
print('he' in str)
print('aa' in str)
print('he' not in str)
结果:
True
False
False
for循环遍历
str = "apple"
for i in str:
    print(i)
结果:
a
p
p
l
e

字符串常用操作

#大小写判断
>>> 'Hello'.istitle()   #首字母为大写,其余为小写
True
>>> 'hello'.istitle()
False
>>> 'hello'.isupper()	#判断全大写
False
>>> 'hello'.islower()	#判断全小写
True
>>> 'hello'.upper()		#转换为大写
'HELLO'
>>> 'hELLo'.lower()		#转换为小写
'hello'
>>> 'hEllo'.upper()
'HELLO'
>>> 'hEllo'.title()		#转换为首字母为大写,其余为小写
'Hello'	

#字符串中首尾字符判断
>>> 'helloword'.startswith('hello')		#判断字符串开头是否符合
True
>>> 'helloword'.startswith('er')             
False
>>> 'helloword'.endswith('ord')			#判断字符串结尾是否符合
True
>>> 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值