字符串¶

生成字符串¶

Python中可以使用一对单引号''或者双引号""生成字符串。

In [1]:

  1. s = "hello, world"
  2. print s
  1. hello, world

In [2]:

  1. s = 'hello world'
  2. print s
  1. hello world

简单操作¶

加法:

In [3]:

  1. s = 'hello ' + 'world'
  2. s

Out[3]:

  1. 'hello world'

字符串与数字相乘:

In [4]:

  1. "echo" * 3

Out[4]:

  1. 'echoechoecho'

字符串长度:

In [5]:

  1. len(s)

Out[5]:

  1. 11

字符串方法¶

Python是一种面向对象的语言,面向对象的语言中一个必不可少的元素就是方法,而字符串是对象的一种,所以有很多可用的方法。

跟很多语言一样,Python使用以下形式来调用方法:

  1. 对象.方法(参数)

分割¶

s.split()将s按照空格(包括多个空格,制表符\t,换行符\n等)分割,并返回所有分割得到的字符串。

In [6]:

  1. line = "1 2 3 4 5"
  2. numbers = line.split()
  3. print numbers
  1. ['1', '2', '3', '4', '5']

s.split(sep)以给定的sep为分隔符对s进行分割。

In [7]:

  1. line = "1,2,3,4,5"
  2. numbers = line.split(',')
  3. print numbers
  1. ['1', '2', '3', '4', '5']

连接¶

与分割相反,s.join(str_sequence)的作用是以s为连接符将字符串序列str_sequence中的元素连接起来,并返回连接后得到的新字符串:

In [8]:

  1. s = ' '
  2. s.join(numbers)

Out[8]:

  1. '1 2 3 4 5'

In [9]:

  1. s = ','
  2. s.join(numbers)

Out[9]:

  1. '1,2,3,4,5'

替换¶

s.replace(part1, part2)将字符串s中指定的部分part1替换成想要的部分part2,并返回新的字符串。

In [10]:

  1. s = "hello world"
  2. s.replace('world', 'python')

Out[10]:

  1. 'hello python'

此时,s的值并没有变化,替换方法只是生成了一个新的字符串。

In [11]:

  1. s

Out[11]:

  1. 'hello world'

大小写转换¶

s.upper()方法返回一个将s中的字母全部大写的新字符串。

s.lower()方法返回一个将s中的字母全部小写的新字符串。

In [12]:

  1. "hello world".upper()

Out[12]:

  1. 'HELLO WORLD'

这两种方法也不会改变原来s的值:

In [13]:

  1. s = "HELLO WORLD"
  2. print s.lower()
  3. print s
  1. hello world
  2. HELLO WORLD

去除多余空格¶

s.strip()返回一个将s两端的多余空格除去的新字符串。

s.lstrip()返回一个将s开头的多余空格除去的新字符串。

s.rstrip()返回一个将s结尾的多余空格除去的新字符串。

In [14]:

  1. s = " hello world "
  2. s.strip()

Out[14]:

  1. 'hello world'

s的值依然不会变化:

In [15]:

  1. s

Out[15]:

  1. ' hello world '

In [16]:

  1. s.lstrip()

Out[16]:

  1. 'hello world '

In [17]:

  1. s.rstrip()

Out[17]:

  1. ' hello world'

更多方法¶

可以使用dir函数查看所有可以使用的方法:

In [18]:

  1. dir(s)

Out[18]:

  1. ['__add__',
  2. '__class__',
  3. '__contains__',
  4. '__delattr__',
  5. '__doc__',
  6. '__eq__',
  7. '__format__',
  8. '__ge__',
  9. '__getattribute__',
  10. '__getitem__',
  11. '__getnewargs__',
  12. '__getslice__',
  13. '__gt__',
  14. '__hash__',
  15. '__init__',
  16. '__le__',
  17. '__len__',
  18. '__lt__',
  19. '__mod__',
  20. '__mul__',
  21. '__ne__',
  22. '__new__',
  23. '__reduce__',
  24. '__reduce_ex__',
  25. '__repr__',
  26. '__rmod__',
  27. '__rmul__',
  28. '__setattr__',
  29. '__sizeof__',
  30. '__str__',
  31. '__subclasshook__',
  32. '_formatter_field_name_split',
  33. '_formatter_parser',
  34. 'capitalize',
  35. 'center',
  36. 'count',
  37. 'decode',
  38. 'encode',
  39. 'endswith',
  40. 'expandtabs',
  41. 'find',
  42. 'format',
  43. 'index',
  44. 'isalnum',
  45. 'isalpha',
  46. 'isdigit',
  47. 'islower',
  48. 'isspace',
  49. 'istitle',
  50. 'isupper',
  51. 'join',
  52. 'ljust',
  53. 'lower',
  54. 'lstrip',
  55. 'partition',
  56. 'replace',
  57. 'rfind',
  58. 'rindex',
  59. 'rjust',
  60. 'rpartition',
  61. 'rsplit',
  62. 'rstrip',
  63. 'split',
  64. 'splitlines',
  65. 'startswith',
  66. 'strip',
  67. 'swapcase',
  68. 'title',
  69. 'translate',
  70. 'upper',
  71. 'zfill']

多行字符串¶

Python 用一对 """ 或者 ''' 来生成多行字符串:

In [19]:

  1. a = """hello world.
  2. it is a nice day."""
  3. print a
  1. hello world.
  2. it is a nice day.

在储存时,我们在两行字符间加上一个换行符 '\n'

In [20]:

  1. a

Out[20]:

  1. 'hello world.\nit is a nice day.'

使用 () 或者 \ 来换行¶

当代码太长或者为了美观起见时,我们可以使用两种方法来将一行代码转为多行代码:

  • ()
  • \

In [21]:

  1. a = ("hello, world. "
  2. "it's a nice day. "
  3. "my name is xxx")
  4. a

Out[21]:

  1. "hello, world. it's a nice day. my name is xxx"

In [22]:

  1. a = "hello, world. " \
  2. "it's a nice day. " \
  3. "my name is xxx"
  4. a

Out[22]:

  1. "hello, world. it's a nice day. my name is xxx"

强制转换为字符串¶

  • str(ob)强制将ob转化成字符串。
  • repr(ob)也是强制将ob转化成字符串。
    不同点如下:

In [23]:

  1. str(1.1 + 2.2)

Out[23]:

  1. '3.3'

In [24]:

  1. repr(1.1 + 2.2)

Out[24]:

  1. '3.3000000000000003'

整数与不同进制的字符串的转化¶

可以将整数按照不同进制转化为不同类型的字符串。

十六进制:

In [25]:

  1. hex(255)

Out[25]:

  1. '0xff'

八进制:

In [26]:

  1. oct(255)

Out[26]:

  1. '0377'

二进制:

In [27]:

  1. bin(255)

Out[27]:

  1. '0b11111111'

可以使用 int 将字符串转为整数:

In [28]:

  1. int('23')

Out[28]:

  1. 23

还可以指定按照多少进制来进行转换,最后返回十进制表达的整数:

In [29]:

  1. int('FF', 16)

Out[29]:

  1. 255

In [30]:

  1. int('377', 8)

Out[30]:

  1. 255

In [31]:

  1. int('11111111', 2)

Out[31]:

  1. 255

float 可以将字符串转换为浮点数:

In [32]:

  1. float('3.5')

Out[32]:

  1. 3.5

格式化字符串¶

Python用字符串的format()方法来格式化字符串。

具体用法如下,字符串中花括号 {} 的部分会被format传入的参数替代,传入的值可以是字符串,也可以是数字或者别的对象。

In [33]:

  1. '{} {} {}'.format('a', 'b', 'c')

Out[33]:

  1. 'a b c'

可以用数字指定传入参数的相对位置:

In [34]:

  1. '{2} {1} {0}'.format('a', 'b', 'c')

Out[34]:

  1. 'c b a'

还可以指定传入参数的名称:

In [35]:

  1. '{color} {n} {x}'.format(n=10, x=1.5, color='blue')

Out[35]:

  1. 'blue 10 1.5'

可以在一起混用:

In [36]:

  1. '{color} {0} {x} {1}'.format(10, 'foo', x = 1.5, color='blue')

Out[36]:

  1. 'blue 10 1.5 foo'

可以用{<field name>:<format>}指定格式:

In [37]:

  1. from math import pi
  2.  
  3. '{0:10} {1:10d} {2:10.2f}'.format('foo', 5, 2 * pi)

Out[37]:

  1. 'foo 5 6.28'

具体规则与C中相同。

也可以使用旧式的 % 方法进行格式化:

In [38]:

  1. s = "some numbers:"
  2. x = 1.34
  3. y = 2
  4. # 用百分号隔开,括号括起来
  5. t = "%s %f, %d" % (s, x, y)

In [39]:

  1. t

Out[39]:

  1. 'some numbers: 1.340000, 2'

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/02-python-essentials/02.04-strings.ipynb