python 教程 第二章、 类型

第二章、 类型

常量

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.大小写敏感。

服务项目 技术咨询 微信图书 微信视频 微信代码 定制开发 其他福利
服务入口 QQ群有问必答
查看详情
一本书解决90%问题
查看详情
微信开发视频
小程序开发视频
免费代码
¥1888阿里云代金券
查看详情
营销工具
微信特异功能
原文地址:https://www.cnblogs.com/txw1958/p/2209847.html