Python 1 - 基本数据类型

2016-11-15  本文已影响41人  扫地阿伟
python.png
Python数据类型

1. 命名规则

2. 逻辑型

定义:False True
运算符:& | not

3. 数值型

运算符:+ - * /

# 取整 //
7 // 4 
--> 1
# 取余 %
7 % 4
 --> 3
# 乘方 **
2 ** 3 
--> 8

# 注意浮点数计算
a = 2.1;
b = 4.2;
a + b 
--> 6.300000001
(a + b) == 6.3 
--> False

# WHY?
a = 2.3;
b = 4.2;
(a + b) == 6.5 
--> True

4. 字符型

定义: '' '' ''
# 反斜杠(\)表示转义字符
print('hello,\n how are you?')
--> hello,
--> how are you?
# 不想让反斜杠转义,可在字符串前面加 r ,表示原始字符
print(r'hello,\n how are you?)
--> hello,\n how are you?

# 反斜杠还可以作为续行符,表示下一行是上一行延续
# 还可以使用 """ ...""" 或者 '''...'''跨多行
s = '''
abcd
efg
'''
print(s) 
--> abcd
--> efg

# 字符串之间可以使用 '+' 或者 '*'
print('abc' + 'def', 'my' * 3)
--> abcdef mymymy

# Python 索引方式两种:
# 1.从左到右,索引从0开始;
# 2.从右到左,索引从-1开始;
# 没有单独的字符,一个字符就是长度为1的字符串
Word = 'Python'
print(Word[0],Word[-1])
--> P n
s = 'a'
len('s')
--> 1

# 对字符串切片,获取一段子串
# 用冒号分开两个索引,形式为 变量[头下标:尾下标]
# 截取范围前闭后开,且两个索引都可以省略
Str = 'iLovePython'
Str[0:2]
--> 'iL'
Str[3:]
--> 'vePython'
 Str[:5]
--> 'iLove'
Str[:]
--> 'iLovePython'
 Str[-1:]
--> 'n'
Str[-5:-1]
--> 'ytho'

# Python字符串不可改变
Str[0] = 'a'
--> TypeError: 'str' object does not support item assignment

# 检测开头和结尾
url = 'http://www.python.org'
url.startswith('http:')        # starts 有 s
--> True
url.endswith('.com')        # endswith 有 s
--> False
choices = ('http:','https')
url.startswith(choices)
--> True
choices = ['http:','https']
url.startswith(choices)
--> False

# 查找字符串,区分大小写
Str = 'Python'
Str.find('y')
--> 1
Str.find('Y')
--> -1    
# 忽略大小写的查找
import re
Str = 'Python,YELL'
re.findall('y', Str, flags = re.IGNORECASE)
--> ['y', 'Y']

# 查找与替换
text = 'hello, how, what, why'
text.replace('hello', 'hi')
--> 'hi, how, what, why'
text
--> 'hello, how, what, why'
text = text.replace('hello', 'hi')
text
--> 'hi, how, what, why'
# 忽略大小写的替换
import re
text = 'UPPER PYTHON, lower python, Mixed Python'
re.sub('python','java',text,flags = re.IGNORECASE)
--> 'UPPER java, lower java, Mixed java'

# 合并拼接字符串
parts = ['yo','what\'s','up']
' ' .join(parts)
--> "yo what's up"
',' .join(parts)
-->  "yo,what's,up"
上一篇 下一篇

猜你喜欢

热点阅读