《Py4Inf-06-Strings-PrintPy4Inf-06-Strings-Print》由会员分享,可在线阅读,更多相关《Py4Inf-06-Strings-PrintPy4Inf-06-Strings-Print(8页珍藏版)》请在金锄头文库上搜索。
1、StringsChapter 6Python for Informatics: Exploring IUnless 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
2、 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 rece
3、nt 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 nu
4、mbers 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
5、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 FarYo
6、u 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 gi
7、ves 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 le
8、n(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 co
9、nstruct 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
10、 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 a
11、n 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 i
12、t! 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 invo
13、ke 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/stri
14、ng-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, rstr
15、ip, 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: