Skip to content

Latest commit

 

History

History
275 lines (213 loc) · 4.42 KB

01_输入和输出.md

File metadata and controls

275 lines (213 loc) · 4.42 KB

print

print("HelloWorld")
>>>
HelloWorld

print的美化

  • Json格式的输出
import json

data = [{'a':1, 'b':2, 'c':3}]

# json.dumps将数组变成JSON
data_json = json.dumps(data)
print(data_json)
print(type(data_json))
>>>
[{"a": 1, "b": 2, "c": 3}]
<class 'str'>

# json.loads将JSON变成数组字段
data_raw = json.loads(data_json)
print(data_raw)
print(type(data_raw))
>>>
[{'a': 1, 'b': 2, 'c': 3}]
<class 'list'>
  • pprint
import pprint
import json
from urllib.request import urlopen 

with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
    project_info = json.load(resp)['info']
    pprint.pprint(project_info)
>>>
{'author': 'A. Random Developer',
 'author_email': 'author@example.com',
 'bugtrack_url': None,
 'classifiers': ['Development Status :: 3 - Alpha',
                 'Intended Audience :: Developers',
                 'License :: OSI Approved :: MIT License',
                 'Programming Language :: Python :: 3',
                 'Programming Language :: Python :: 3 :: Only',
                 'Programming Language :: Python :: 3.5',
                 'Programming Language :: Python :: 3.6',
                 'Programming Language :: Python :: 3.7',
                 'Programming Language :: Python :: 3.8',
                 'Topic :: Software Development :: Build Tools'],
 'description': '# A sample Python project\n'
 ...
}

格式化输出

  • 格式化字符串字面值,使用f前缀
year = 2021
month = 5
day = 1

today = f'{year}/{month}/{day}'
print(today)
>>>
2021/5/1
  • %的常见用法

    • %s 字符串,使用str()显示
    • %r 字符串,使用repr()显示
    • %d 十进制整数
    • %f 浮点数
    • %10s 右对齐,十个占位符
    • %-10s 左对齐,十个占位符
    • %.2s 截断两个字符
    • %10.2s 右对齐十个占位符 截断两个字符
    • %f 保留小数点后六位有效数字
    • %.3f 保留三位有效数字
    # %s
    print('%s'%'hello')
    >>>
    hello
    
    # %10s
    print('%10s'%'hello')
    >>>
         hello
      
    # %-10s
    print('%-10s'%'hello')
    >>>
    hello   
    
    # %10.2s
    print('%10.2s'%'hello')
    >>>
            he
      
    # %f
    print('%f'% 1.11)
    >>>
    1.110000
    
    # %.2f
    print('%.2f'% 1.222)
    >>>
    1.22
    • Format
      • 不带参数{}
      • 带数字参数 {1}{2}
      • 带关键字 {a} {b}
      • 索引
      • key参数
    # 不带参数
    print('{},{}'.format('hello','world'))
    >>>
    hello,world
    # 带数字参数
    print('{0},{1}'.format('hello','world'))
    >>>
    hello,world
    
    # 带关键字参数
    print('{a},{b}'.format(a='hello',b='world'))
    >>>
    hello,world
    
    # 索引
    tup = (1,2)
    print('X:{0[0]}; Y:{0[1]};'.format(tup))
    >>>
    X:1; Y:2;
        
    # key参数
    dic = {'a':11, 'b':22}
    print('X: {0[a]}, Y: {0[b]}'.format(dic))
    >>>
    X: 11, Y: 22

IO操作

  • StringIO:把str写入内存中
from io import StringIO

f = StringIO()
f.write('hello')
f.write(' ')
f.write('world')
print(f.getvalue())
>>>
hello world
  • BytesIO:把字节流写入内存
from io import BytesIO

f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())
>>>
b'\xe4\xb8\xad\xe6\x96\x87'
  • with语句
# with语句是一种上下文管理协议
# 通过__enter__()初始化
# 通过__exit__()进行结束和异常处理


# 只读模式
with open('a.txt','r') as f:
    f.readlines()

# 写入模式
with open('a.txt','w') as f:
    f.write()

# 读写模式
with open('a.txt','w+') as f:
    f.write()

# 追加模式
with open('a.txt','a') as f:
    f.readlines()
    f.write()

# 二进制形式
with open('a.txt','ab') as f:
    f.write()
  • csv模块
import csv

# csv的写入

# 表头创建
headers = ['name','age']

# 每行数据
rows = [
    ['xiaoming',12],
    ['xiaohong',23]
]
# 写入操作
with open('first.csv','w') as f:
    f_csv = csv.writer(f)
    f_csv.writerow(headers)
    f_csv.writerows(rows)
    
# 使用字典写入

rows_dict = [
    {'name':'xiaoming','age':12},
    {'name':'xiaohong','age':23}
]

with open('second.csv','w') as f:
    f_csv = csv.DictWriter(f,headers)
    f_csv.writeheader()
    f_csv.writerows(rows_dict)
    
# csv的读取
with open('first.csv','r') as f:
    f_csv = csv.reader(f)
    for row in f_csv:
        print(row)
>>>
['name', 'age']
['xiaoming', '12']
['xiaohong', '23']

输入

name = input('What is your name?')
print('Hello ' + name)