Python3学习笔记

 

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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值