input-与raw_input ·例:比较 >>>x input() >>>x raw input ( "John John >>>x >>>x >>>x input() >>>x raw input ( 3*4+2 3*4+2 >>>x >>>x ·可见raw input()将输入当成字符串数 据。 Lu Chaojun,SJTU 6
input与raw_input • 例:比较 >>>x = input() >>>x = raw_input() "John" John >>>x >>>x >>>x = input() >>>x = raw_input() 3*4+2 3*4+2 >>>x >>>x • 可见raw_input()将输入当成字符串数 据. Lu Chaojun, SJTU 6
字符串操作:取字符 ·字符串是字符序列,可通过位置索引访问每个字 符. <string>[<index-expr>] -对长度为n的字符串,索引可以 人是大于0的数:自左向右为0~n-1,或者 人是负数:自右向左为-1,-2,-3,,-n -例如:若str="Hello Bob",则 strO]或str-9]是'H strl5]或str-4是' str8]或str-1刂是'b' str9]或str-10越界出错
字符串操作:取字符 • 字符串是字符序列,可通过位置索引访问每个字 符. <string>[<index-expr>] – 对长度为n的字符串,索引可以 ©是大于0的数:自左向右为0 ~ n1, 或者 ©是负数:自右向左为1, 2, 3,…, n – 例如:若str = "Hello Bob" ,则 str[0]或str[9]是'H' str[5]或str[4]是' ' str[8]或str[1]是'b' str[9]或str[10]越界出错
字符串操作:取子串 ·切段:取一个索引范围内的字符 <string>[<start>:<end>] -所取子串:位置索引从start~end-1 -start或/和end可省略,缺省值为串的首尾 -例如:若str="Hello Bob",则 strO:3]是'Hel" strl5:9]是'Bob' str:5]即str0:5] str[5:]即strl5,9] str:]即str0:9]
字符串操作:取子串 • 切段:取一个索引范围内的字符. <string>[<start>:<end>] – 所取子串:位置索引从start ~ end1 – start或/和end可省略,缺省值为串的首尾 – 例如:若str = "Hello Bob" ,则 str[0:3]是'Hel' str[5:9]是' Bob' str[:5]即str[0:5] str[5:]即str[5,9] str[:]即str[0:9]
字符串操作:连接 ·两字符串的连接 <stringl><string2> -例如: "Hello"+"Bob"得到"HelloBob" ·一个字符串的重复 -例如: 3*"Hi"和"Hi"*3都得到"HiHiHi'" 。串长度函数len(0
字符串操作:连接 • 两字符串的连接 <string1> + <string2> – 例如: "Hello" + "Bob"得到"HelloBob" • 一个字符串的重复 – 例如: 3*"Hi"和"Hi"*3都得到"HiHiHi" • 串长度函数len()
编程实例:表查找 ·在一个数据表里查找目标 def main(): months="JanFebMarAprMayJunJulAugSepoctNovDec" n input ("Enter month number (1-12):" pos=(n-1)*3 monthAbbr months [pos:pos+3] print "The month abbreviation is",monthAbbr+"." -这是简单查找:利用位置规律来定位. 人例如:定长记录文件 一若是月份全称怎么办?
编程实例:表查找 • 在一个数据表里查找目标 def main(): months="JanFebMarAprMayJunJulAugSepOctNovDec" n = input("Enter month number (1-12): ") pos = (n-1)*3 monthAbbr = months[pos:pos+3] print "The month abbreviation is" ,monthAbbr+"." – 这是简单查找:利用位置规律来定位. ©例如:定长记录文件. – 若是月份全称怎么办?