C++
std::cout << "Hello world!";
// output: Hello world!
Run Code Online (Sandbox Code Playgroud)
Python
print("Hello world!")
# output: Hello world!
Run Code Online (Sandbox Code Playgroud)
那个有效。但是我怎么能在 Python 中做到这一点呢?
std::string name = "Robert";
std::cout << "Hello " << name << ", how are you?";
Run Code Online (Sandbox Code Playgroud) 在 C++ 中,std::endl
用于添加返回并刷新字符串。在Python中,除了特定的用途之外,没有必要使用这个特殊的功能。
可能证明其使用合理的用途之一是将输出重定向到文件,例如:
outfile = open("output_file.txt", 'a')
sys.stdout = outfile
print("Something")
Run Code Online (Sandbox Code Playgroud)
在这种情况下,除非文件被关闭 ( outfile.close()
) 或手动刷新 ( outfile.flush()
),否则文件不会显示其内容。
如果 Python 中存在 C++ 中的等效项std::endl
,则它既可以写入该行又可以刷新文件。
我怀疑这个功能是否存在,但我问这个问题是为了确定。
谢谢 :)