【问题标题】:How can I make my code work if the input is already predetermined?如果输入已经预先确定,我怎样才能使我的代码工作?
【发布时间】:2021-11-30 04:32:54
【问题描述】:

所以我试图假设评分者定义了以下变量

a to be some int
b to be some float
s to be some string

编写一个程序,打印出以下内容,其中 中的值被变量内的实际值替换。但是,您只能使用 ONE print 语句。

// The variable 'a' has value of <a>. //
\\ While the variable 'b' has value of <b>. \\
// Lastly, the variable 's' has value of "<s>". //

例如,如果 a=1、b=1.5 和 s='hi',那么预期的输出是:

// The variable 'a' has value of 1. //
\\ While the variable 'b' has value of 1.5. \\
// Lastly, the variable 's' has value of "hi". /

这是我目前的代码,我是通过 Stack Overflow 用户的帮助获得的

def make_tags(tag, word):
        print("<" + tag + ">" + word + "</" + tag + ">")

但是,当变量已经预先确定时,这不起作用......我应该改变什么??

【问题讨论】:

  • 你想要的输出是什么,你得到的输出是什么?
  • 真的完全不清楚你在问什么以及你描述的情况。你所说的“分级员”是什么意思?
  • 使用f-strings

标签: python list function


【解决方案1】:

我不知道这是不是你的意思,因为你的问题不够清楚,但是你可以使用 fstring 来实现单行打印,

a = 1 
b = 1.5
c = 'hi'
str_example = f'this sentance has an int {a}, a float {b} and a string {c}'
print(str_example)

我的输出是这样的,

this sentance has an int 1, a float 1.5 and a string hi

当您在引号前以字母 f 开始字符串时,可以使用花括号插入变量。

你可以像这样创建你的 fstring,

a = 1 
b = 1.5
c = 'hi'

some_string = f"// The variable 'a' has value of {a}. // \n \\ While the variable 'b' has value of {b}. \\ \n // Lastly, the variable 's' has value of \"{c}\". //"

输出是这样的,

// The variable 'a' has value of 1.
 While the variable 'b' has value of 1.5.
 Lastly, the variable 's' has value of "hi". //

你也可以像这样使用三引号,

a = 1 
b = 1.5
c = 'hi'

some_string = f"""// The variable 'a' has value of {a}. //
\\\ While the variable 'b' has value of {b}. \\\\
// Lastly, the variable 's' has value of "{c}". //"""

你的输出应该是这样的,

// The variable 'a' has value of 1. //
\\ While the variable 'b' has value of 1.5. \\
// Lastly, the variable 's' has value of "hi". //

如果需要将它包装在一个函数中,你可以这样做,

a = 1 
b = 1.5
c = 'hi'

def string_maker(a,b,c):
    return f"""// The variable 'a' has value of {a}. //
\\\ While the variable 'b' has value of {b}. \\\\
// Lastly, the variable 's' has value of "{c}". //"""

print(string_maker(a,b,c))

输出将与上面相同。

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多