Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7662
  • 博文数量: 4
  • 博客积分: 111
  • 博客等级: 入伍新兵
  • 技术积分: 55
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-16 15:23
个人简介

人生苦短

文章分类

全部博文(4)

文章存档

2014年(3)

2010年(1)

我的朋友
最近访客

分类: Python/Ruby

2014-11-17 23:25:00

严格意义上说,字符串是一个单个字符的字符串的序列

字符串操作

点击(此处)折叠或打开

  1. # 举例字符串
  2. S = 'Test'
查看字符串长度

点击(此处)折叠或打开

  1. len(S)
  2. # 结果
  3. # 4
查看第一个字符

点击(此处)折叠或打开

  1. S[0]
  2. # 结果
  3. # 'T'
查看第二个字符

点击(此处)折叠或打开

  1. S[1]
  2. # 结果
  3. # 'e'
查看最后一个

点击(此处)折叠或打开

  1. S[-1]
  2. # 结果
  3. # 't'
查看最后第二个

点击(此处)折叠或打开

  1. S[-2]
  2. # 结果
  3. # 's'
查看第3个和查看最后第二个是等效的

点击(此处)折叠或打开

  1. S[2]
  2. # 结果
  3. # 's'
  4. S[-2]
  5. # 结果
  6. # 's'
  7. S[len(S)+-2]
  8. # 结果
  9. # 's'
分片(slice)

点击(此处)折叠或打开

  1. # X[I:J]表示从X中第I个字符开始取,直到但不包含第J个字符

  2. S[1:3]
  3. # 结果
  4. # 'es'

  5. S[1:]
  6. # 结果
  7. # 'est'

  8. S[:-1]
  9. # 结果
  10. # 'Tes'

  11. S[:]
  12. # 结果
  13. # 'Test'
字符串相加

点击(此处)折叠或打开

  1. S + 'xyz'
  2. # 结果
  3. # 'Testxyz'

  4. S
  5. # 结果,注意不会改变S的值
  6. # 'Test'
字符串乘积

点击(此处)折叠或打开

  1. S * 8
  2. # 结果
  3. # 'TestTestTestTestTestTestTestTest'
字符串的不可变性

点击(此处)折叠或打开

  1. S[0] = 'w'
  2. # 结果
  3. # TypeError: 'str' object does not support item assignment
查看字符串的所有属性和方法

点击(此处)折叠或打开

  1. dir(S)
  2. # 结果
  3. # ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
针对单个属性和方法进行查看

点击(此处)折叠或打开

  1. help(S.join)
  2. # 结果
  3. # Help on built-in function join:

  4. join(...)
  5.     S.join(iterable) -> string
  6.     
  7.     Return a string which is the concatenation of the strings in the
  8.     iterable. The separator between elements is S.

阅读(295) | 评论(0) | 转发(0) |
0

上一篇:Python对象类型 数字

下一篇:没有了

给主人留下些什么吧!~~