由于毕业论文是文本分析相关,涉及python数据挖掘方面,故开始学习python,并记录学习历程。
学习笔记一:
python中的一切皆为对象(跟javascript一样),主要的数据类型有:
- 不可变变量: int, string, tuple(元祖)
- 可变变量: list(列表), dict(字典)
python中的字符串
(1)三引号(三个单/双引号)可以换行
>>> a = ''' hello
... my name is
... "tom"''' # 三个引号作为多行输入的结束
>>> a
'hello\n my name is\n "tom"'
变量的类型转换
不同类型变量之间的操作是需要提前进行变量类型转换:
>>> a = '1111';
>>> b=2;
>>> print( int(a)+b ) #将a转为int类型,然后进行运算
1113
>>> print( a + str(b) ); #将b转为str类型
11112
>>> print( a+b ) # 如果不进行类型转换直接操作,将报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>>
如上面可以看到:当a为string类型,而b为int类型,当直接做相加运算时,会报错,必须在运算之前将其转为相同数据类型之后进行相应操作。
布尔类型
python中的bool类型有: True和False两种。
>>> a =1;
>>> b="1";
>>> a == b; # 数据类型不同,直接比较返回False
False
>>> type(a); # a的数据类型为 int
<type 'int'>
>>> type(b) # b的数据类型为 str
<type 'str'>
>>> a == int(b); # 进行比较操作前,将其转为相同类型之后,为 True
True
>>>
tips: python中三引号的作用是,可以包含多行内容;相当于进行多行输入。
python中字符串的替换和查找
- 字符串的替换: replace
>>> a = 'hello,python'
>>> id(a); # 记录a的id
4427810440
>>> a.replace('hello','hi'); #将a中的hello替换成hi
'hi,python'
>>> a #发现a的值实际上并没有改变
'hello,python'
>>> id(a); # 此时a的id也未变
4427810440
>>> b= a.replace('hello','hi'); # 将替换之后返回的值赋给b
>>> b
'hi,python' # 发现返回的值为替换之后的值
>>> id(b) # 同时b的id与a的id并不相同
4427807168
>>> a = b; # 将b赋值给a
>>> a # 此时a的值改变
'hi,python'
>>> id(a); # a的id同时改变,变为与b的id相同
4427807168
>>> id(b);
4427807168
上面的例子说明replace替换函数并不会改变源字符串,除非将替换之后返回的值付给源字符串,才会真正达到替换的效果。
- 字符串的查找 find
find函数是为了查询字符串中是否有子字符串,若存在返回子字符串在父字符串中第一次出现的下标,如不存在返回-1
>>> a = 'this is my first time to learn python'
>>> a.find('my'); # my字符串在a中第一次出现的下标为8
8
>>> a.find('a'); # a在learn中出现,返回位置27
27
>>> a.find('zero'); # 没找到子字符串返回-1
-1
>>>
当然,字符串查找中,find函数参数start和end为可选参数,a.find(‘to’, 4,10); 查找a中从下标4到10的字符串种子字符串出现的下标位置。
python中字符串的格式化
1. %格式化方式,字符串的使用%s,数字使用%d
>>> a = "this is an %s" % "apple"
>>> a
'this is an apple'
>>> a = 'I have %d %s' % (10,'apples');
>>> a
'I have 10 apples'
2. format格式化方式
# 方式一
>>> a = "I have {} {}".format(12, 'apples');
>>> a
'I have 12 apples'
# 方式二
# format可以不按照顺序来格式化字符串
>>> a = "I have {1} {0}".format('apples',12);
>>> a
'I have 12 apples'
# 方式三
>>> a = "I have {num} {fruit}".format(fruit="apples",num=12);
>>> a
'I have 12 apples'
# 方式四
>>> a = "I have %(num)d %(fruit)s" % {'fruit':'apple','num':12}
>>> a
'I have 12 apples'
python中字符串的重复
# python中可以通过字符串*num的方式重复字符串
>>> a = 'hello world'*10;
'hello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello world'
python中字符串的子字符串
(1)索引运算符:获得索引位置上的子字符
>>> a = 'hello python';
>>> a[0] # 获取字符串a的第0个字符
'h'
>>> a[7]; # 获取字符串a的第7个字符
'y'
(2)切片运算符:[a, b]获得a到b-1之间的子字符串
>>> a = 'hello python'
>>> a[:5] # 获取字符串a中0-(5-1)的子字符串
'hello'
>>> a[6:] # 获取字符串a中6-(a.length-1)的子字符串
'python'
>>> a[6,9] # 获取字符串a中6-8的子字符串
'pyt'