【问题标题】:How do I get parentheses around my variable? [duplicate]如何在变量周围加上括号? [复制]
【发布时间】:2019-01-25 22:13:01
【问题描述】:

我正在做我的第一个作业,但我不知道如何在打印变量时将括号括起来。

我试过了 (xs) {xs} [xs} 但是没有人在它周围加上括号

(print)("Hello user! Welcome to the program!")
 name = input("What is your name?")
(print)("Hello", name)
x = input("What is your favorite number?")
y = int(x) // 2
xs = str(x)
ys = str(y)
z = ("Did you know that half of your favorite number" + ' ' + xs + ' ' + 'is' + ' ' + ys + '?')

打印(z)

对于代码的倒数第二行,我想说的是你知道你的数字 (5) 的一半是 2 吗?

5 只是一个示例数字,但我希望它在括号中!

【问题讨论】:

  • 将倒数第二行设为z = "Did you know that half of your favorite number" + ' (' + xs + ') ' + 'is' + ' ' + ys + '?'
  • 帮自己一个忙,按照一个好的教程来学习语言。你的代码中有太多的括号。在此处阅读有关字符串格式的信息:pyformat.info 和 google python f-string 如果您确实在 python 3.6+ 上 - 如果您只是用谷歌搜索“如何在字符串 python 中打印数字”,您将获得数千个解决此问题的方法。教程:docs.python.org/3/tutorial .. 从解释字符串的地方开始打印:docs.python.org/3/tutorial/introduction.html#stringsdocs.python.org/3/tutorial/…

标签: python python-3.x


【解决方案1】:

这样做:

z = ("Did you know that half of your favorite number" + ' (' + xs + ') ' + 'is' + ' ' + ys + '?')

【讨论】:

  • 更好用str.format()
  • 当然,我只是在修改他的代码..对他/她来说更容易!
【解决方案2】:

您只需要在正确的位置添加穿刺术,如下所示:

z = ("你知道你喜欢的那个数字的一​​半吗" + ' (' + xs + ') ' + 'is' + ' ' + ys + '?')

【讨论】:

    【解决方案3】:

    我不确定这是否是您需要的,但您只需在变量周围连接 "("")"

    >>> y = "number"
    >>> print ( "(" + y + ")" )
    (number)
    

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 1970-01-01
      • 2014-05-31
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 2013-07-12
      相关资源
      最近更新 更多