资源预览内容
第1页 / 共8页
第2页 / 共8页
第3页 / 共8页
第4页 / 共8页
第5页 / 共8页
亲,该文档总共8页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述
StringsChapter 6Python for Informatics: Exploring Informationww.pythonlearn.comUnless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License.htp:/creativecommons.org/licenses/by/3.0/.Copyright 2010- Charles SeveranceString Data TypeA string is a sequence of charactersA string literal uses quotes Hello or “Hello”For strings, + means “concatenate”When a string contains numbers, it is stil a stringWe can convert numbers in a string into a number using int() str1 = Hello str2 = there bob = str1 + str2 print bobHellothere str3 = 123 str3 = str3 + 1Traceback (most recent cal last):File , line 1, in TypeError: cannot concatenate str and int objects x = int(str3) + 1 print x124 Reading and ConvertingWe prefer to read data in using strings and then parse and convert the data as we needThis gives us more control over error situations and/or bad user inputRaw input numbers must be converted from strings name = raw_input(Enter:)Enter:Chuck print nameChuck apple = raw_input(Enter:)Enter:100 x = apple - 10Traceback (most recent cal last):File , line 1, in TypeError: unsupported operand type(s) for -: str and int x = int(apple) - 10 print x90Loking Inside StringsWe can get at any single character in a string using an index specified in square bracketsThe index value must be an integer and starts at zeroThe index value can be an expression that is computed fruit = banana letter = fruit1 print lettera n = 3 w = fruitn - 1 print wn0b1a2n3a4n5aA Character To FarYou wil get a python error if you attempt to index beyond the end of a string.So be careful when constructing index values and slices zot = abc print zot5Traceback (most recent cal last):File , line 1, in IndexError: string index out of range Strings Have LengthThere is a built-in function len that gives us the length of a string fruit = banana print len(fruit)60b1a2n3a4n5aLen Function fruit = banana x = len(fruit) print x6len()functionbanana (a string)6(a number)A function is some stored code that we use. A function takes some input and produces an output.Guido wrote this codeLen Functiondef len(inp):blahblahfor x in y:blahblahA function is some stored code that we use. A function takes some input and produces an output. fruit = banana x = len(fruit) print x6banana (a string)6(a number)Loping Through StringsUsing a while statement and an iteration variable, and the len function, we can construct a lop to lok at each of the letters in a string individualyfruit = bananaindex = 0while index s = Monty Python print s0:4Mont print s6:7P print s6:20Python0M1o2n3t4y56P7y8t9h10o11nIf we leave off the first number or the last number of the slice, it is asumed to be the beginning or end of the string respectivelySlicing Strings s = Monty Python print s:2Mo print s8:thon print s:Monty Python0M1o2n3t4y56P7y8t9h10o11nString ConcatenationWhen the + operator is applied to strings, it means concatenation a = Hello b = a + There print bHelloThere c = a + + There print cHello There Using in as an OperatorThe in keyword can also be used to check to see if one string is in another stringThe in expression is a logical expression and returns True or False and can be used in an if statement fruit = banana n in fruitTrue m in fruitFalse nan in fruitTrue if a in fruit : . print Found it!. Found it! String Comparisonif word = banana:print All right, bananas.if word banana:print Your word, + word + , comes after banana.else:print All right, bananas.String LibraryPython has a number of string functions which are in the string libraryThese functions are already built into every string - we invoke them by appending the function to the string variableThese functions do not modify the original string, instead they return a new string that has been altered greet = Hello Bob zap = greet.lower() print zaphello bob print greetHello Bob print Hi There.lower()hi therehttp:/docs.python.org/lib/string-methods.html stuff = Hello world type(stuff) dir(stuff)capitalize, center, count, decode, encode, endswith, expandtabs, find, format, index, isalnum, isalpha, isdigit, islower, ispace, istitle, isupper, join, ljust, lower, lstrip, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfillhttp:/docs.python.org/lib/string-methods.htmlstr.capitalize()str.center(width, fillchar)str.endswith(suffix, start, end)str.find(sub, start, end)str.lstrip(chars)str.replace(old, new, count)str.lower()str.rstrip(chars)str.strip(chars)str.upper()http:
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号