python自学之《Python程序设计 (第3版)》——关于序列:字符串、列表和文件

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

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


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

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

  1 # username.py
  2 # 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 names
  8     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 username
 15     print("Your username is:", uname)
 16 
 17 main()
  1 #month.py
  2 #A program to print the abbreviation of a month, given its number
  3 def main():
  4     #months is used as a lookup table
  5     months = "JanFebMarAprMayJunJulAugSepOctNovDec"
  6 
  7     n = int(input("Enter a month number (1-12): "))
  8 
  9     #compute starting position of month n in months
 10     pos = (n-1) * 3
 11 
 12     #Grab the appropriate slice from months
 13     monthAbbrev = months[pos:pos+3]
 14 
 15     #print the result
 16     print("The month abbreviation is", monthAbbrev + ".")
 17 
 18 main()
  1 # month2.py
  2 # A program to print the month abbreviation, given its number.
  3 
  4 def main():
  5     # months is a list used as a lookup table
  6     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 of
  2 #     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 ecode
  9     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 values
 14     for ch in message:
 15         print(ord(ch), end=" ")
 16 
 17     print() # blank line before prompt
 18 
 19 main()
  1 # A program to convert a sequence of Unicode numbers into
  2 #    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 encode
  9     inString = input("Please enter the Unicode-encode message: ")
 10     message = " "
 11 
 12     # Loop through each substring and build Unicode message
 13     message = " "
 14     for numStr in inString.split():
 15         codeNum = int(numStr)     # convert digits to a number
 16         message = message + chr(codeNum) # concatentate character to message
 17         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:  S

The decoded message is:  St

The decoded message is:  Str

The decoded message is:  Stri

The decoded message is:  Strin

The decoded message is:  String

The decoded message is:  Strings

The decoded message is:  Strings 

The decoded message is:  Strings a

The decoded message is:  Strings ar

The decoded message is:  Strings are

The decoded message is:  Strings are 

The decoded message is:  Strings are F

The decoded message is:  Strings are Fu

The decoded message is:  Strings are Fun

The 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.py
  2 # A program to calculate the value of some change in dollars
  3 # 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 + pennies
 14 
 15     print("The total value of your change is ${0}.{1:0>2}"
 16         .format(total//100, total%100))
 17 main()
~         

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

  1 # userfile.py
  2 # 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 names
  9     infileName = input("What file are the names in? ")
 10     outfileName = input("What file should the usernames go in? ")
 11 
 12     # open the files
 13     infile = open(infileName, "r")
 14     outfile = open(outfileName, "w")
 15 
 16     # process each line of the input file
 17     for line in infile:
 18         # get the first and last names from line
 19         first, last = line.split()
 20         # create the username
 21         uname = (first[0]+last[:7]).lower()
 22         # write it to the output file
 23         print(uname, file=outfile)
 24 
 25     # close both files
 26     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
>>> 

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值