一、输入
1、单行输入input()和readline()(两者返回值均为str)
(1)例子
import sys
line = sys.stdin.readline() 或者 line=input()
for i in line:
print(i+'hello')
输入:
23 nia
readline()输出:
2hello
3hello
hello
nhello
ihello
ahello
hello
input()输出:
2hello
3hello
hello
nhello
ihello
ahello
(2)两者区别
注意到,回车作为结束命令,在readline()中也作为字符被算入了输入中,而在input()中则不算入。
2、多行输入readlines()(返回值为list,但list中的值的类型为str)
(1)例子
import sys
line = sys.stdin.readlines()
for v in line:
print(v+'hello')
输入:
23
nia
CTRL+D
(ps:其中CTRL+D被用来结束命令)
输出:
23
hello
nia
hello
注意到,回车符也被算入了输入中。
3、输入中多余字符的处理
(1)通过指定分割符对字符串切片——split(str, num)(函数返回值为list)
a、句法
str.split(str='', num=string.count(str))
第一个str——指明对象为字符串(注意对象不能为列表list)
第二个str——分割符,默认为所以空字符,包括空格、换行(\n)、制表符(\t)
num——分割次数
c、例子
str = 'Line1-abcdef \nLine2-abc \nLine4-abcd'
print(str.split( ))
print(str.split(' ', 1 ))
输出:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
(2)去除字符串换首尾指定的字符——strip()
a、句法
str.strip(‘char’);
char默认为空格、换行符等等。注意对象为str,不能为列表list。返回值为str
b、例子
str = "0000000 Runoob 0000000";
print(str.strip('0')) # 去除首尾字符 0
str2 = " Runoob "# 去除首尾空格
print(str2.strip())
输出:
二、输出
1、连接字符串——join()函数
a、句法
str.join(sequence)
其中,str——连接方式,如空格,逗号,-等
sequence——要连接的元素序列
b、实例:输出列表元素,以空格/逗号为分隔符,注意要求最后一个数字无空格
l=[1,2,3,4]
print(' '.join(str(i) for i in l ))
(注意只能连接字符串,此例list中的数字为int类型,所以要用str强制类型转换)
输出:
1 2 3 4
或者
l=['1','2','3','4']
print(' '.join(l))
输出同样的结果:
1 2 3 4
2、精度控制
(1)保留两位小数
print('%.2f'%s)
其中,s为数字