课程的安排没有面面俱到,但会让你很快明白Python的不同,以及最应该掌握的东西。
做完课后练习,如果你仔细看看Test的部分,能够发现google测试框架gtest的影子。
google Python course 地址:google Python course
每个 Python 的字符串实际上都是一个\’str\’类
In [1]:string2 =\'hello,world!\'
In [2]:type(string2)
字符串可以使用单引号和双引号,通常我们更习惯于使用单引号
反斜杠(eg. n \\\’ \\\”) 在单引号和双引号中都可以正常使用
在双引号中可以是使用单引号,反之在单引号中也可以使用双引号,这并没有值得奇怪的地方
在字符串的末尾使用 表示换行
使用三个单引号或者双引号,表示这是多行的文本。该方法也可以用来做注释。
Python的字符串是\”不可变的\”,意味着创建之后不允许修改。 虽然字符串不能被改变,但是我们可以创建新的字符串,并通过计算得到一个新的字符串。eg. \’hello\’ +\’world\’ 两个字符串连接,形成一个新的字符串 \’helloworld\’
In [3]: string1 =\'hello\'
In [4]: string = \' world\'
In [5]: string1 + string
Out[5]: \'hello world\'
字符串中的字符,可以通过列表的[ ]语法访问,像C++和Java一样。Python 字符串的索引是从0开始的。
与java不同的是,字符串连接中的\’+\’不能自动将其他类型转换为字符类型。我们需要显式的通过str()函数进行转换。
In [3]: pi = 3.14
In [4]: str1 = \'PI is \'
In [5]: print str1 + pi
Traceback (most recent call last):
File \"\", line 1, in
TypeError: cannot concatenate \'str\' and \'float\' objects
In [6]: print str1+str(pi)
out [6]: PI is 3.14
针对Python3,对于整数除法,我们应该是用两个斜杠 //
在Python2中,默认 / 即是整数除 ,在Python3中应该使用 //
In [1]: 6 / 5
out[1]:1.2
In [2]: 6 // 5
out[2]: 1
r\’text\’表示一个原生字符串。原生字符串会忽略特殊字符,直接打印字符串内的内容。
In [7]: string3 =\'hello,\\n\\n world!\'
In [8]: str_raw =r\'hello,\\n\\n world!\'
In [9]: print(string3)
hello,
world!
In [10]: print(str_raw)
hello,\\n\\n world!
字符串方法
s.lower(), s.upper() –字符串大小写转换
s.strip() — 去掉字符串首尾的空格
s.isalpha()/s.isdigit()/s.isspace()… — 测试字符串是否为全部字符组成/数字/空格
s.startswith(\’other\’), s.endswith(\’other\’) –测试字符串是否以给定的字符串开头或结尾
s.find(\’other\’) — 查找给定字符串,返回首次匹配的索引,如果没有找到返回-1
s.replace(\’old\’, \’new\’) –字符串替换
s.split(\’delim\’) — 以指定字符,拆分字符串,返回拆分后的字符串列表。默认按照空格拆分。
s.join(list) — 以指定字符连接列表
list =[\'I\',\'am\',\'good\',\'man\']
>>> \',\'.join(list)
\'I,am,good,man\'
字符串切片
s=\'hello\'
s[1:4] is \’ell\’ — 从索引1开始,但不包括4
s[1:] is \’ello\’ — 从1开始,一直到字符串结尾
s[:] is \’Hello\’ — 整个字符串
s[1:100] is \’ello\’ — 从1开始,一致到字符串结尾(最大值超过字符串长度,将以字符串长度截断)