如何删除随机模块中的括号

2024-09-28 21:59:31 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

import random
name="srp"
age=14
gender="male"
vote="N/A"
def about_user():
    aboutusr1="Your name is",name,".\nYou are",age,"years old.\nYour gender is",gender,".\nFun fact -",vote," :)"
    aboutusr2="You are my master whose name is",name,".\nYour age is",age,"and your gender is",gender,".\nAlso, I know that",vote
    L1=[aboutusr1, aboutusr2]
    c=random.choice(L1)
    print(c)
abs=input("Ask me :")
if "about me" in abs:
    about_user()

输出:

Ask me :about me ('Your name is', 'srp', '.\nYou are', 14, 'years old.\nYour gender is', 'male', '.\nFun fact -', 'N/A', ' :)')

但我不想要开始和结束括号,单引号。此外,新行的\n等内容也不会打印。 请帮帮我


Tags: nameageyourisrandomgenderaremale
2条回答

更改aboutusr1aboutusr2如下(使用str.format()

aboutusr1= "Your name is {}.\nYou are {} years old.\nYour gender is {}.\nFun fact - {} :)".format(name,age,gender,vote)
aboutusr2= "You are my master whose name is {}.\nYour age is {} and your gender is {}.\nAlso, I know that {}".format(name,age,gender,vote)

输出

You are my master whose name is srp.
Your age is 14 and your gender is male.
Also, I know that N/A

或者正如@sim在注释中解释的那样,在代码中使用print(*c)*willunpack the tuple

如果使用python 3,则可以使用fstring:

import random
name="srp"
age=14
gender="male"
vote="N/A"
def about_user(name,age,gender,vote):
    aboutusr1=f"Your name is {name},\nYou are {age},years old.\nYour gender is {gender}.\nFun fact - {vote} :)"
    aboutusr2=f"You are my master whose name is {name}.\nYour age is {age}, and your gender is {gender}.\nAlso, I know that {vote}"
    L1=" ".join([aboutusr1, aboutusr2])
    #Don't understand why this line
    #c=random.choice(L1)
    print(L1)


abs=input("Ask me :")
if "about me" in abs:
    about_user(name,age,gender,vote)

相关问题 更多 >