Chinaunix首页 | 论坛 | 博客
  • 博客访问: 570393
  • 博文数量: 80
  • 博客积分: 2393
  • 博客等级: 大尉
  • 技术积分: 1434
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-03 21:46
个人简介

己所不欲勿施于人!

文章分类

全部博文(80)

文章存档

2017年(1)

2016年(9)

2014年(1)

2013年(17)

2012年(5)

2011年(13)

2010年(9)

2009年(8)

2008年(17)

分类: Python/Ruby

2016-08-16 11:20:22

Google Python Course,是目前我见过最好的Python课程。
课程的安排没有面面俱到,但会让你很快明白Python的不同,以及最应该掌握的东西。
做完课后练习,如果你仔细看看Test的部分,能够发现google测试框架gtest的影子。
google Python course 地址:http://https://developers.google.com/edu/python/

  1. 每个 Python 的字符串实际上都是一个'str'类 
    >>> string2 ='hello,world!'
    >>> type(string2)
    < class str >
    >>>  
  2. 字符串可以使用单引号和双引号,通常我们更多的使用单引号
  3. 反斜杠(eg. \n \’\")在单引号和双引号中都可以正常使用
  4. 在双引号中可以是使用单引号,反之在单引号中也可以使用双引号,这并没有值得奇怪的地方
  5. 在字符串的末尾使用 \ 表示换行
  6. 使用三个单引号或者双引号,表示这是多行的文本。该方法也可以用来做注释。
  7. Python的字符串是"不可变的",意味着创建之后不允许修改。 虽然字符串不能被改变,但是我们可以创建新的字符串,并通过计算得到一个新的字符串。eg. 'hello' +'world'   两个字符串连接,形成一个新的字符串 'helloworld' 
    >>> string1 ='hello'
    >>> string = ' world'
    >>> string1 + string
    'hello world'
    >>> 
  8. 字符串中的字符,可以通过列表的[ ]语法访问,像C++和Java一样。Python 字符串的索引是从0开始的。
  9. 与java不同的是,字符串连接中的'+'不能自动将其他类型转换为字符类型。我们需要显式的通过str()函数进行转换。 
    >>> pi = 3.14
    >>> str1 = 'PI is '
    >>> print str1 + pi
    Traceback (most recent call last):
    File "", line 1, in 
    TypeError: cannot concatenate 'str' and 'float' objects
    >>> print str1+str(pi)
    PI is 3.14
    >>>  
  10. 针对Python3,对于整数除法,我们应该是用两个斜杠 * // *
    在Python2中,默认 / 即是整数除 ,在Python3中应该使用 // 
    >>> 6 / 5
    1.2
    >>> 6 // 5
    1
  11. r'text'表示一个原生字符串。原生字符串会忽略特殊字符,直接打印字符串内的内容。
    >>> string3 ='hello,\n\n world!'
    >>> str_raw =r'hello,\n\n world!'
    >>> print string3
    hello,


    world!
    >>> 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开始,一致到字符串结尾(最大值超过字符串长度,将以字符串长度截断)
阅读(1504) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~