Getting python - user interaction

A receiving user input

# 在Python3:input会将用户输入的所有内容都存成字符串类型
username = input("请输入您的账号:")     # input:egon
# 此时username = “egon” 
print(username, type(username))        # output:egon <class 'str'>

# 数据类型的转换
age = input("请输入的你的年龄: ")  # input:18
# 此时 age = “18”
age=int(age) # int只能将纯数字的字符串转成整型
# 此刻 age = 18
print(age, type(age))   # output:18 <class 'int'>

Precautions:

# 在python2中:
# input():用法与python3的input一模一样
# input(): 要求用户必须输入一个明确的数据类型,输入的是什么类型,就存成什么类型
# 举例
age=input(">>>>>>>>>>>>>>>>>>>>>: ") 
>>>>>>>>>>>>>>>>>>>>>: 18
>>> age,type(age)   # output (18, <type 'int'>)

x=input(">>>>>>>>>>>>>>>>>>>>>: ")
>>>>>>>>>>>>>>>>>>>>>: 1.3
>>> x,type(x)   # output:(1.3, <type 'float'>)

Second, the output string formatted

1. '%' output format (here either -% means%)

# 值按照位置与%s一一对应,少一个不行,多一个也不行
res="my name is %s my age is %s" %('egon',"18") 
print(res)      # output:my name is egon my age is 18
res="my name is %s my age is %s" %("18",'egon') 
print(res)      # output:my name is 18 my age is egon

According to the above example, the output value of% s was found to be one to one, or appear like the second example will be shown

Of course, in addition to '% s' other operator, as shown below

Operator% Types of Precautions
%s String You may receive any type
%d Integer Only receive int
%f Floating-point type You may receive and float int

In the form of a dictionary by value, to break the limit position

res="我的名字是 %(name)s 我的年龄是 %(age)s" %{"age":"18","name":'egon'}
print(res)      # output:我的名字是 egon 我的年龄是 18

2.str.format: Good compatibility

# 按照位置传值
res='我的名字是 {} 我的年龄是 {}'.format('egon',18)
print(res)      # output:我的名字是 egon 我的年龄是 18

3.f: only launched after python3.5

x = input('your name: ')        # input:egon
y = input('your age: ')         # input:18
res = f'我的名字是{x} 我的年龄是{y}'
print(res)      # output:我的名字是egon 我的年龄是18

4. filled formatting

#先取到值,然后在冒号后设定填充格式:[填充字符][对齐方式][宽度]
# *<10:左对齐,总共10个字符,不够的用*号填充
print('{0:*<10}'.format('开始执行')) # output:开始执行******
# *>10:右对齐,总共10个字符,不够的用*号填充
print('{0:*>10}'.format('开始执行')) # output:******开始执行
# *^10:居中显示,总共10个字符,不够的用*号填充
print('{0:*^10}'.format('开始执行')) # output:***开始执行

The accuracy ary

print('{salary:.3f}'.format(salary=1232132.12351))  #精确到小数点后3位,四舍五入,结果为:1232132.124
print('{0:b}'.format(123))  # 转成二进制,结果为:1111011
print('{0:o}'.format(9))  # 转成八进制,结果为:11
print('{0:x}'.format(15))  # 转成十六进制,结果为:f
print('{0:,}'.format(99812939393931))  # 千分位格式化,结果为:99,812,939,393,931

Guess you like

Origin www.cnblogs.com/zhuyouai/p/12423404.html