Google Python Course---Strings

Google Python Course,是目前我见过最好的Python课程。

课程的安排没有面面俱到,但会让你很快明白Python的不一样,以及最应该掌握的东西。
作完课后练习,若是你仔细看看Test的部分,可以发现google测试框架gtest的影子。
google Python course 地址:google Python coursejava

  • 每一个 Python 的字符串实际上都是一个'str'类python

    In [1]:string2 ='hello,world!' 
    In [2]:type(string2)
    <class str>
  • 字符串可使用单引号和双引号,一般咱们更习惯于使用单引号git

  • 反斜杠(eg. n \' \") 在单引号和双引号中均可以正常使用框架

  • 在双引号中能够是使用单引号,反之在单引号中也可使用双引号,这并无值得奇怪的地方函数

  • 在字符串的末尾使用 表示换行测试

  • 使用三个单引号或者双引号,表示这是多行的文本。该方法也能够用来作注释。google

  • Python的字符串是"不可变的",意味着建立以后不容许修改。 虽然字符串不能被改变,可是咱们能够建立新的字符串,并经过计算获得一个新的字符串。eg. 'hello' +'world' 两个字符串链接,造成一个新的字符串 'helloworld'spa

In [3]: string1 ='hello'
     In [4]: string = ' world'
     In [5]: string1 + string 
     Out[5]: 'hello world'
  • 字符串中的字符,能够经过列表的[ ]语法访问,像C++和Java同样。Python 字符串的索引是从0开始的。code

  • 与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'

字符串切片

hello

s='hello'

  • s[1:4] is 'ell' -- 从索引1开始,但不包括4

  • s[1:] is 'ello' -- 从1开始,一直到字符串结尾

  • s[:] is 'Hello' -- 整个字符串

  • s[1:100] is 'ello' -- 从1开始,一致到字符串结尾(最大值超过字符串长度,将以字符串长度截断)

相关文章
相关标签/搜索