python自学之《Python程序设计 (第3版)》(3)

编程入门 行业动态 更新时间:2024-10-08 06:28:19

python自学之《Python<a href=https://www.elefans.com/category/jswz/34/1771020.html style=程序设计 (第3版)》(3)"/>

python自学之《Python程序设计 (第3版)》(3)

第 5 章 序 列 : 字 符 串 、 列 表 和 文 件

文本在程序中由字符串数据类型表示。你可以将字符串视为一个字符序列。在第 2 章中你已了解到,通过用引号将一些字符括起来形成字符串字面量。Python 还允许字符串由单引号(撇号)分隔。它们没有区别,但用时一定要配对。字符串也可以保存在变量中,像其他数据一样


>>> greet = "Hello Bob"
>>> greet[0]
'H'
>>> print(greet[0])
H
>>> 

索引和切片是将字符串切成更小片段的有用操作。字符串数据类型还支持将字符串放在一起的操作。连接(+)和重复(*)是两个方便的运算符。连接通过将两个字符串“粘合”在一起来构建字符串;重复通过字符串与多个自身连接,来构建字符串。另一个有用的函数是 len,它告诉你字符串中有多少个字符。最后,由于字符串是字符序列,因此可以使用 Python 的 for 循环遍历这些字符。

  1 # username.py2 # Simple string processing program to generate usernames.3 4 def main():5     print("This program generates computer usernames.\n")6 7     #get user's first and last names8     first = input("Please enter your first name (all lowercase): ")9     last = input("Please enter your last name (all lowercase): ")10 11     #concatenate first initial with 7 chars of the last name.12     uname = first[0] + last[:7]13 14     #output the username15     print("Your username is:", uname)16 17 main()
  1 #month.py2 #A program to print the abbreviation of a month, given its number3 def main():4     #months is used as a lookup table5     months = "JanFebMarAprMayJunJulAugSepOctNovDec"6 7     n = int(input("Enter a month number (1-12): "))8 9     #compute starting position of month n in months10     pos = (n-1) * 311 12     #Grab the appropriate slice from months13     monthAbbrev = months[pos:pos+3]14 15     #print the result16     print("The month abbreviation is", monthAbbrev + ".")17 18 main()
  1 # month2.py2 # A program to print the month abbreviation, given its number.3 4 def main():5     # months is a list used as a lookup table6     months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",7               "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]8     n = int(input("Enter a month number (1-12): "))9     print("The month abbreviation is", months[n-1] + ".")10 11 main()

字符串不可变,但列表可以变。

>>> ord("a")
97
>>> ord("A")
65
>>> ord(97)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: ord() expected string of length 1, but int found
>>> chr(97)
'a'
>>> chr(90)
'Z'
>>> 

>>> coords = input("Enter the point coordinates (x,y): ").split(",")
Enter the point coordinates (x,y): 3.4, 6.25
>>> coords
['3.4', ' 6.25']
  1 # A program to convert a textual message into a sequence of2 #     numbers, utilizing the underlying Unicode encoding.3 4 def main():5     print("This program converts a textual message into a sequence")6     print("of numbers representing the Unicode encoding of the message.\n")7 8     #Get the message to ecode9     message = input("Please enter the message to encode: ")10 11     print("\nHere are the Unicode codes:")12 13     #  Loop through the message and print out the Unicode values14     for ch in message:15         print(ord(ch), end=" ")16 17     print() # blank line before prompt18 19 main()
  1 # A program to convert a sequence of Unicode numbers into2 #    a string of text.3 4 def main():5     print("This program converts a sequence of Unicode numbers into")6     print("the string of text that it represents.\n ")7 8     #Get the message to encode9     inString = input("Please enter the Unicode-encode message: ")10     message = " "11 12     # Loop through each substring and build Unicode message13     message = " "14     for numStr in inString.split():15         codeNum = int(numStr)     # convert digits to a number16         message = message + chr(codeNum) # concatentate character to message17         print("\nThe decoded message is:", message)18 19 main()
This program converts a sequence of Unicode numbers into
the string of text that it represents.Please enter the Unicode-encode message: 83 116 114 105 110 103 115 32 97 114 101 32 70 117 110 33                                                        The decoded message is:  SThe decoded message is:  StThe decoded message is:  StrThe decoded message is:  StriThe decoded message is:  StrinThe decoded message is:  StringThe decoded message is:  StringsThe decoded message is:  Strings The decoded message is:  Strings aThe decoded message is:  Strings arThe decoded message is:  Strings areThe decoded message is:  Strings are The decoded message is:  Strings are FThe decoded message is:  Strings are FuThe decoded message is:  Strings are FunThe decoded message is:  Strings are Fun!

避免不断重复复制消息的一种方法是使用列表。消息可以作为字符列表来累积,其中每个新字符附加到已有列表的末尾。记住,列表是可变的,所以在列表的末尾添加将“当场”改变列表,而不必将已有内容复制到一个新的对象中 ① 。一旦我们累积了列表中的所有字符,就可以用 join 操作将这些字符一下子连接成一个字符串。①实际上,如果 Python 没有空间放置新的项,列表确实需要在幕后重新复制,但这是罕见的情况。

>>> "Hello {0} {1}, you may have won ${2}".format("Mr.", "Smith", 10000)
'Hello Mr. Smith, you may have won $10000'
>>> "This int, {0:5}, was placed in a field of width 5".format(7)
'This int,     7, was placed in a field of width 5'
>>> "This int, {0:10}, was placed in a field of width 10".format(7)
'This int,          7, was placed in a field of width 10'
>>> "This float, {0:10.5}, has width 10 and precision 5".format(3.1415926)
'This float,     3.1416, has width 10 and precision 5'
>>> "This float, {0:10.5f}, is fixed at 5 decimal places".format(3.1415926)
'This float,    3.14159, is fixed at 5 decimal places'
>>> "This float, {0:0.5}, has width 0 and precision 5".format(3.1415926) 
'This float, 3.1416, has width 0 and precision 5'
>>> "Compare {0} and {0:0.20}".format(3.14)
'Compare 3.14 and 3.1400000000000001243'
>>> 

>>> "left justification: {0:<5}".format("Hi!")
'left justification: Hi!  '
>>> "right justification: {0:>5}".format("Hi!")
'right justification:   Hi!'
>>> "centered: {0:^5}".format("Hi!")
'centered:  Hi! '
>>> 

  1 # change2.py2 # A program to calculate the value of some change in dollars3 # This version represents the total cash in cents.4 5 def main():6     print("Change Counter\n")7     print("Please enter the count of each coin type.")8     quarters = int(input("Quarters: "))9     dimes = int(input("Dimes: "))10     nickels = int(input("Nickels: "))11     pennies = int(input("Pennies: "))12 13     total = quarters * 25 + dimes * 10 + nickels * 5 + pennies14 15     print("The total value of your change is ${0}.{1:0>2}"16         .format(total//100, total%100))17 main()
~         

  1 # userfile.py2 # program to create a file of usernames in batch mode.3 4 def main():5     print("This program creates a file of usernames from a")6     print("file of names.")7 8     # get the file names9     infileName = input("What file are the names in? ")10     outfileName = input("What file should the usernames go in? ")11 12     # open the files13     infile = open(infileName, "r")14     outfile = open(outfileName, "w")15 16     # process each line of the input file17     for line in infile:18         # get the first and last names from line19         first, last = line.split()20         # create the username21         uname = (first[0]+last[:7]).lower()22         # write it to the output file23         print(uname, file=outfile)24 25     # close both files26     infile.close()27     outfile.close()28 29     print("Usernames have been written to", outfileName)30 31 main()

>>> s1 = "spam"
>>> s2 = "ni!"
>>> "The Knights who say, " + s2
'The Knights who say, ni!'
>>> 3 * s1 + 2 * s2
'spamspamspamni!ni!'
>>> s1[1]
'p'
>>> s1[1:3]
'pa'
>>> s1[2] + s2[:2]
'ani'
>>> s1 + s2[-1]
'spam!'
>>> s1.upper()
'SPAM'
>>> s2.upper().ljust(4) * 3
'NI! NI! NI! '
>>> for ch in "aardvark":
...     print(ch)
... 
a
a
r
d
v
a
r
k
>>> for w in "Now is the winter of our discontent...".split():
...     print(w)
... 
Now
is
the
winter
of
our
discontent...
>>> for w in "Mississippi".split("i"):
...     print(w, end=" ")
... 
M ss ss pp  >>> msg = ""
>>> for ch in "secret":
...     msg = msg + chr(ord(ch)+1)
... 
>>> print(ms)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'ms' is not defined
>>> print(msg)
tfdsfu
>>> 

>>> "Looks like {1} and {0} for breakfast".format("eggs","spam")
'Looks like spam and eggs for breakfast'
>>> "There is {0} {1} {2} {3}".format(1, "spam", 4, "you")
'There is 1 spam 4 you'
>>> "Hello {0}".format("Susan", "Computewell")
'Hello Susan'
>>> "{0:0.2f} {0:0.2f}".format(2.3, 2.3468)
'2.30 2.30'
>>> "{7.5f} {7.5f}".format(2.3, 2.3468)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
IndexError: Replacement index 7 out of range for positional args tuple
>>> "Time left {0:02}:{1:05.2f}".format(1, 37.374)
'Time left 01:37.37'
>>> "{1:3}".format("14")
Traceback (most recent call last):File "<stdin>", line 1, in <module>
IndexError: Replacement index 1 out of range for positional args tuple
>>> 

更多推荐

python自学之《Python程序设计 (第3版)》(3)

本文发布于:2024-02-28 00:04:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1766999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:程序设计   python   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!