1. print如何不换行输出?
答: 首先我们看下print的定义
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
"""
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
"""
pass
重点观察下end参数,默认是'\n'
所以如果想实现不换行只需要给end重新赋值就可以了,例如:
s1="hello "
s2="world!"
print(s1, end='')
print(s2)
2. 如何输出一个空的换行?
答: print()
3. 如何删除字符串末尾的空行,或者有没有类似trim()函数?
答: 只删除末尾的空白字符使用rstrip()函数,这里需要注意下,rstrip()只是暂时删除,如果想让它生效就重新赋一次值.
4. 如何下载文件?
import urllib.request
import time
url = 'http://g.hiphotos.baidu.com/image/pic/item/5243fbf2b2119313562db8dc68380cd791238d74.jpg'
print("downloading with urllib...")
start=time.time()
f = urllib.request.urlopen(url)
data = f.read()
with open("demo2.jpg", "wb") as code:
code.write(data)
end=time.time()
print("time consuming: %.4fs" % (end-start))
5. 下载带进度显示
import urllib.request
import time
# url = 'http://g.hiphotos.baidu.com/image/pic/item/5243fbf2b2119313562db8dc68380cd791238d74.jpg'
url='http://www.waveshare.net/datasheet/Microchip_PDF/PIC16F877A.PDF'
lastprecent=0
def report_hook(count, block_size, total_size):
global lastprecent #必须告诉编译器lastprecent是全局的,否则会报UnboundLocalError错误!!!
# if lastprecent != 100 * count * block_size/ total_size:
current=100 * count * block_size/ total_size
current=int(current)
if current != lastprecent:
lastprecent=current
print('%02d%%' % lastprecent)
print("downloading with urllib...")
start=time.time()
# urllib.urlretrieve("http://sports.sina.com.cn/", reporthook= report_hook)
# f = urllib.request.urlopen(url)
urllib.request.urlretrieve(url,filename='demo.pdf',reporthook=report_hook)
# data = f.read()
# with open("demo2.pdf", "wb") as code:
# code.write(data)
end=time.time()
print("time consuming: %.4fs" % (end-start))