python 教程 第二章、 类型
来源:互联网 发布:西安网站seo 编辑:程序博客网 时间:2024/05/16 11:06
第二章、 类型
常量
5,1.23,9.25e-3,’This is a string’,”It’s a string!”
1) 数
整数:2
长整数:
浮点数:3.23,52.3E-4
复数:-5+4j,2.3-4.6j
ac =-8.33 +1.2j
print ac.real #-8.33
print ac.imag #1.2
print ac.conjugate() #(-8.33-1.2j)
二进制:0b1000
八进制:0o307
十六进制:0xFF
2) 字符串
单引号(')
'Quote me on this'
双引号(")
"What's your name?"
三引号('''或""") 可以在三引号中自由的使用单引号和双引号
'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
原始字符串(前缀r或R)raw strings
r"Newlines are indicated by \n"。
Unicode字符串(前缀u或U)
u"This is a 中文 string."
Byte strings(in 3.0)
S = b'spam'
字符串的方法
name = 'Swaroorp' # This is a string object
print name.encode('latin-1') #Swaroorp
print name.startswith('Swa') #True
print name.endswith('spam') #False
print name.find('war') #1
print name.find('warx') #-1
print name.rstrip() #remove whitespace #Swaroorp
print name.isdigit() #False
print name.replace('oo', 'xx') #Swarxxrp
print name.upper() #swaroorp
print name.lower() #swaroop
print name.split('r') #['Swa', 'oo', 'p']
print map(ord, name) #[83, 119, 97, 114, 111, 111, 114, 112]
print map(chr, (map(ord, name))) #['S', 'w', 'a', 'r', 'o', 'o', 'r', 'p']
print '-'.join(name) #S-w-a-r-o-o-r-p
print 'spam' in name #False
for x in name: print(x) #s w a r o o r p)
print [c * 2 for c in name] #['SS', 'ww', 'aa', 'rr', 'oo', 'oo', 'rr', 'pp']
了解这些方法的完整列表,请参见help(str)。
注意:
1.字符串不可变
2.字符串自动连接. 'What\'s' 'your name?'= "What's your name?"。
3.没有Char类型
4.一定要用自然字符串处理正则表达式,否则会需要使用很多的反斜杠
Format方法
类似参数传递
>>> template = '{0}, {1} and {2}' # By position
>>> template.format('spam', 'ham', 'eggs')
'spam, ham and eggs'
>>> template = '{motto}, {pork} and {food}' # By keyword
>>> template.format(motto='spam', pork='ham', food='eggs')
'spam, ham and eggs'
>>> template = '{motto}, {0} and {food}' # By both
>>> template.format('ham', motto='spam', food='eggs')
'spam, ham and eggs'
3) 转义符(\)
'What\'s your name?'
行末的单独一个反斜杠表示字符串在下一行继续
4) 布尔型
True False
"spam" True
"" False
[] False
{} False
1 True
0.0 False
None False
5) 变量
标识符命名
1. 字母或下划线开头.
2. 其他为字母,下划线,数字。
3.大小写敏感。
- python 教程 第二章、 类型
- python 教程 第二章、 类型
- Python核心教程(第二章)
- awk教程-第二章
- 第二章 安装Python
- python参考手册 第二章
- python第二章
- Python读书笔记-第二章
- python第二章
- 第二章 Python简介
- python强化-第二章
- 第二章 Python起步
- python核心编程(第二版)参考答案(自制)--第七章·映像和集合类型
- C#教程第二课:表达式,类型和变量
- C#教程第二课:表达式,类型和变量
- C#教程第二课:表达式,类型和变量
- C#教程第二课:表达式,类型和变量
- 第二章—基本类型
- 处理错误:error while loading shared libraries: libgtk-x11-2.0.so.0
- Using Beyond Compare with Version Control Systems(ZZ)
- eclipse中的设计模式
- python 教程 第一章、 简介
- 利用SecureCRT上传、下载文件(使用sz与rz命令),超实用!
- python 教程 第二章、 类型
- 2013 Multi-University Training Contest 1
- python 教程 第三章、 运算符与表达式
- python 教程 第四章、 控制流
- python 教程 第五章、 函数
- python 教程 第六章、 模块
- python 教程 第七章、 数据结构
- python 教程 第八章、 第一个python程序
- python 教程 第九章、 类与面向对象