首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

Google's Python Class 二 (Python Strings)

2012-10-15 
Googles Python Class 2 (Python Strings)原文:http://code.google.com/edu/languages/google-python-cla

Google's Python Class 2 (Python Strings)

原文:http://code.google.com/edu/languages/google-python-class/strings.html

Python并没有一个单独的“字符”类型,所有的字符都是以字符串的形式存在.

String Slices (字符串切割)

"slice" 关键词是适用于序列元素的很方便的工具 -- 尤其是字符串和列表. s[start:end]表示从start开始到end(不包含end)位置结束. 加入我们有一个 s = "Hello"

Google's Python Class 二 (Python Strings)

  • s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4
  • s[1:] is 'ello' -- 不写边界默认为0或总长度
  • s[:] is 'Hello' -- 遍历整个字符串的常用方法
  • s[1:100] is 'ello' -- 不会报错

    与正数对应,负数作为索引会从字符串的末尾开始计数:

    • s[-1] is 'o' -- last char (1st from the end)
    • s[-4] is 'e' -- 4th from the end
    • s[:-3] is 'He' -- going up to but not including the last 3 chars.
    • s[-3:] is 'llo' -- starting with the 3rd char from the end and extending to the end of the string.

      slices有一个众所周知的小技巧,?s[:n] + s[n:] == s. 这段代码在n越界的情况下也会正常执行. 这些特性同样也适用于list,我们会在后面讲到。

      String %

      Python有一个与 printf() 类似的工具. ?可以使用后面的变量替换printf中的% ?(%d int, %s string, %f/%g floating point),如右侧的元组(tuple) ?(元组是一组被逗号风格的,以圆括号包含的一组数):


热点排行