#String和文件处理——EX11-14

  • String的使用
script, user_name = argv #argv: Argument variable参数变量
print(f"Hi {user_name}, I'm the {script} script.")

如上,f-string是3.6推出的,很遗憾,我的3.5版本不能使用,但是可以用str.format()

print("Hi {}, I'm the {} script.".format(user_name,script))

  • 传输
from sys import argv #把sys模组(module)import进来

想对python脚本传参数,那么就要就要使用命令行参数的支持,省得每次去改脚本。
输入的argv参数被视作string类型
在传输时,要注意要unpack的个数应该与Powershell中输入的参数个数匹配,否则会出现如下提醒:
这里写图片描述
也要注意这里运行的代码不再只是python ex11.py, 而变成了python ex11.py str1 str2 str3 (因为这里我们定义过4个argv)

from sys import argv
# read the WYSS section for how to run this
script, first, second, third = argv

print("The script is called:", script)
print("The first variable is:", first)
print("The second variable is:", second)
print("The third variable is:", third)

  • Input函数的使用
pompt = '>'
likes = input(pompt) #输出“>_________”输入内容后赋值给likes
age = input("How old are you?")
height = input("How tall are you?")
weight = input("How much do you weigh?") 

print(f"So, you're {age} old, {height} tall and {weight} heavy")

Exemple

from sys import argv

script, user_name = argv
prompt = '>'

print("Hi {}, I'm the {} script.".format(user_name,script))
print("I'd like to ask you a few questions.")
print("Do you like me {}?".format(user_name))
likes = input(prompt)

print("Where do you live {}?".format(user_name))
lives = input(prompt)

print("What kind of computer do you have?")
computer = input(prompt)

print("""
Alright, so you said {} about liking me. 
You live in {}. Not sure where that is.
And you have a {} computer. Nice""".format(likes,lives,computer)) 

Powershell运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Poisson_SHAN/article/details/81301422
今日推荐