python3的多行输入

Python3多行输入

1、input().split()用法

host, port, username, passwd, dbname = input("请输入服务器地址,端口号,用户名,密码及数据库名,空格隔开:").split()   
# 注意input()的返回类型是str
print(host,port,username,passwd,dbname)

结果:

请输入服务器地址,端口号,用户名,密码及数据库名,空格隔开:10.1.1.71 22 root 123456 db_name

10.1.1.71 22 root 123456 db_name

注意返回的类型为str,如果是整数需要转换为int才可以使用

nm = list(map(int,input().split(" ")))
N = nm[0]
M = nm[1]

2、map()的用法

map(function, iterable, ...)
#       1.function:函数
#    2.iterable:一个或多个序列
#返回值:
#       python3.x返回迭代器,所以python3.x要加list将迭代器转化为列表

举例:

def f(x):
    return x*x
print(list(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
# 输出
[1, 4, 9, 10, 25, 36, 49, 64, 81]

匿名函数:

print(list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])))
# 输出
[1, 4, 9, 16, 25]

3、str.split()用法

str.split(str = "", num = string.count(str))
# str -- 分隔符(默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等)
# num -- 分隔次数,默认为-1,即分割所有
# 返回值:分割后的字符串列表

举例:

txt = "Google#Facebook#Runoob#Taobao"
x = txt.split("#", 1)
print(x)
# 输出结果
['Google', 'Facebook#Runoob#Taobao']

4、str.strip()用法

str.strip([chars])
# char -- 移除字符串头尾指定的字符序列,默认为空格或换行符
# 返回:移除字符串头尾指定的字符串生成的新字符串

举例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
str = "123abcrunoob321"
print (str.strip( '12' ))  # 字符序列为 12
# 输出
3abcrunoob3

5、连续多行输入的写法

while True:
    try:
        m = int(input().strip())
        ...
    except EOFError:
        break