文章目录
变量
- 变量名第一个字符必须是字母表中字母或下划线 _ 。
- 变量名其他的部分由字母、数字和下划线组成。
- 变量名对大小写敏感。
Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。
>>> a=1
>>> id(a)
9322464
>>> id(1)
9322464
>>> c=b=a
>>> id(c)
9322464
>>> id(b)
9322464
#变量a、b、c并没有地址,而是在使用后使用了1的同一地址
python基本内置数据类型
数字类
- 整型(Int) - 通常被称为是整型或整数,是正或负整数,不带小数点。Python3 整型是没有限制大小的,可以当作 Long 类型使用,所以 Python3 没有 Python2 的 Long 类型。
>>> a=1
>>> a
1
>>> type(a) #检测数据类型
<class 'int'>
- 浮点型(float) - 浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250)
>>> b=1.34
>>> b
1.34
>>> type(b)
<class 'float'>
- 布尔型(bool)-布尔类型只有True和False两种值,0或空表示False,非0或者非空表示True,(非0即真)
>>> a = 1
>>> bool(a)
True
>>> bool(0)
False
>>> bool('') #此处为空,空为False
False
>>> bool(' ') #此处不为空,是空格
True
>>> bool('redhat')
True
- 复数( (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'>
字符串
字符串定义
- 可以用单引号 (’…’) 或双引号 ("…") 标识
- 单引号 (’…’) 中,若有需要单引号需要显示,需要 \ 来转义引号
>>> 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
>>>