背景
面试题案例: 123和“123”一样么?
- 从数字角度讲
- 从程序语言的识别来讲
>>> a = 123
>>> stra = "123"
>>> a == stra
False
>>> print a
123
>>> print stra
123
>>> a + stra
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
数字
整型
>>> num1 = 123
>>> type(num1)
<type 'int'>
>>> type(123)
<type 'int'>
长整形
>>> num2 = 999999999999999
>>> type(num2)
<type 'int'>
强制定义为长整型: num3 = 123L
>>> num3 = 123L
>>> type(num3)
<type 'long'>
浮点型:表示小数
>>> f1 = 12
>>> type(f1)
<type 'int'>
>>> f2 = 12.0
>>> type(f2)
<type 'float'>
复数类型:
- python对复数提供内嵌支持,eg: 3.14j, 8.32e-36j
>>> c = 3.14
>>> type(c)
<type 'float'>
>>> c = 3.14j
>>> type(c)
<type 'complex'>
字符串
字符串的定义
# 字符串定义的第一种方式:
>>> str1 = 'our company is westos'
# 字符串定义的第二种方式:
>>> str2 = "our company is westos"
# 字符串定义的第三种方式:
>>> str3 = """our company is westos"""
>>> type(str1)
<type 'str'>
>>> type(str2)
<type 'str'>
>>> type(str3)
<type 'str'>
>>> say = 'let\'s go'
>>> say
"let's go"
>>> say = "let's go "
>>> say
"let's go "
- 转义符号
>>> mail = "tom: hello i am westos "
>>> print mail
tom: hello i am westos
>>> mail = "tom:\n hello\n i am westos "
>>> print mail
tom:
hello
i am westos
- 三重引号
- 块注释
- 函数的doc文档
- 字符串格式化
>>> mail = """tom:
... i am jack
... good luck
... """
>>> print mail
tom:
i am jack
good luck
>>> mail
'tom:\n\ti am jack\n\tgood luck\n'
字符串索引
>>> a = 'abcde'
>>> type(a)
<type 'str'>
>>> a[0]
'a'
>>> a[1]
'b'
>>> a[3]
'd'
>>> a[0]+a[1]
'ab'
>>> a[0]+a[2]
'ac'
字符串切片
>>> a
'abcde'
>>> a[1:5:2]
'bd'
>>> a[1:5] //代表切片取出第2个到第4个
'bcde'
>>> a[:5]
'abcde'
>>> a[4:]
'e'
>>> a[4:1] //python中默认是从左向右取值
''
>>> a[4:1:-1] //当步长为-1时,从右向左取值
'edc'
>>> a[:]
'abcde'
>>> a[-1]
'e'
>>> a[-4:-1] //代表倒数第2个到倒数第4个切片
'bcd'
>>> a[-2:-4]
''
>>> a[-2:-4:1]
''
>>> a[-2:-4:-1]
'dc'