《简明Python教程》之输入与输出

来源:互联网 发布:2016年离婚率数据 编辑:程序博客网 时间:2024/06/07 08:19

用户输入内容

def reverse(text):    return text[::-1]def is_palindrome(text):    return text == reverse(text)something = input("Enter text: ")if is_palindrome(something):    print("Yes, it is a palindrome")else:    print("No, it is not a palindrome")

输出:

Enter text: sirNo, it is not a palindromeEnter text: madamYes, it is a palindrome

切片功能翻转文本,seq[a:b] 来从位置 a 开始到位置 b 结束来对序列进行切片。第三个参数来确定切片的步长(Step)。默认的步长为 1,它会返回一份连续的文本。如果给定一个负数步长,如 -1,将返回翻转过的文本。

input() 函数接受一个字符串作为参数,并将其展示给用户。返回用户输入的文本。

文件

poem = '''\Programming is funWhen the work is doneif you wanna make your work also fun:    use Python!''' # 打开文件以编辑('w'riting)f = open('poem.txt', 'w') # 向文件中编写文本f.write(poem) # 关闭文件f.close() # 如果没有特别指定, # 将假定启用默认的阅读('r'ead)模式f = open('poem.txt')while True:    line = f.readline()    # 零长度指示 EOF    if len(line) == 0:        break    # 每行(`line`)的末尾    # 都已经有了换行符    #因为它是从一个文件中进行读取的    print(line, end='') # 关闭文件f.close()

输出:

Programming is funWhen the work is doneif you wanna make your work also fun:    use Python!

file 类
内置的 open、close 方法,read、readline、write 方法
阅读模式(’r’),写入模式(’w’)和追加模式(’a’)
文本模式(’t’)、二进制模式(’b’)
如果没有指定打开模式,默认“阅读文本文件。
readline按行读取,空行为结束。

Pickle标准模块

Pickle可以将任何纯 Python 对象存储到一个文件中,并在稍后将其取回。这叫作持久地(Persistently)存储对象

import pickle # The name of the file where we will store the objectshoplistfile = 'shoplist.data' # The list of things to buyshoplist = ['apple', 'mango', 'carrot'] # Write to the filef = open(shoplistfile, 'wb') # Dump the object to a filepickle.dump(shoplist, f)f.close() # Destroy the shoplist variabledel shoplist # Read back from the storagef = open(shoplistfile, 'rb') # Load the object from the filestoredlist = pickle.load(f)print(storedlist)

输出:

['apple', 'mango', 'carrot']

pickle 模块的 dump 函数。这一过程被称作封装(Pickling)。
pickle 模块的 load 函数接收返回的对象。这个过程被称作拆封(Unpickling)。

Unicode

unicode 类型,它全都以字母 u 开头,例如 u"hello world"
当我们阅读或写入某一文件或当我们希望与互联网上的其它计算机通信时,我们需要将我们的 Unicode 字符串转换至一个能够被发送和接收的格式,这个格式叫作“UTF-8”。我们可以在这一格式下进行读取与写入,只需使用一个简单的关键字参数到我们的标准 open 函数中:

 # encoding=utf-8import iof = io.open("abc.txt", "wt", encoding="utf-8")f.write(u"Imagine non-English language here")f.close()text = io.open("abc.txt", encoding="utf-8").read()print(text)

使用 Unicode 字面量编写程序时,必须确保 Python 程序已被告知我们使用的是 UTF-8,因此我们必须将 # encoding=urf-8 这一注释放置在我们程序的顶端。

使用 io.open 并提供了“编码(Encoding)”与“解码(Decoding)”参数来告诉 Python 我们正在使用 Unicode