Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
setfill和setwpython等效吗? 我目前正在移植一些C++代码到Python,但是没有找到如何翻译这个: print std::setfill('0') << std::setw(2) << std::hex << myVar << std::dec << " " print std::setfill('0')_Python_C++_Std - Fatal编程技术网

setfill和setwpython等效吗? 我目前正在移植一些C++代码到Python,但是没有找到如何翻译这个: print std::setfill('0') << std::setw(2) << std::hex << myVar << std::dec << " " print std::setfill('0')

setfill和setwpython等效吗? 我目前正在移植一些C++代码到Python,但是没有找到如何翻译这个: print std::setfill('0') << std::setw(2) << std::hex << myVar << std::dec << " " print std::setfill('0'),python,c++,std,Python,C++,Std,没有直接等效项,但您可以使用format函数转换要显示的每个值。有关格式规范,请参阅 print '{:02x}'.format(myVar) 我来这里是想找一个与std::setw(n)相当的。出于好奇,我使用了'{:>n}'。格式(nbr) 例如: [13]:“{:>2}”中的。格式(1) Out[13]:“1” [14]:“{:>2}”格式(10) Out[14]:“10” 你看起来不是很努力,是不是''*n返回任意字符n次%x”%myVar将myVar格式化为十六进制。但谁会先写这样的

没有直接等效项,但您可以使用
format
函数转换要显示的每个值。有关格式规范,请参阅

print '{:02x}'.format(myVar)

我来这里是想找一个与std::setw(n)相当的。出于好奇,我使用了
'{:>n}'。格式(nbr)

例如:

[13]:“{:>2}”中的
。格式(1)
Out[13]:“1”
[14]:“{:>2}”格式(10)
Out[14]:“10”

你看起来不是很努力,是不是<代码>''*n返回任意字符n次<代码>%x”%myVar将myVar格式化为十六进制。但谁会先写这样的东西呢?如果
myVar
的语义要求这样的格式,那么您需要编写一个单独的操纵器来执行此操作,以便与所有具有该语义的变量一起使用。(在Python中,我能想到的唯一方法就是编写一个函数,使用所需的格式进行转换并返回字符串。)当然,还有:您不会将格式返回到
std::dec
;在你改变它之前,你会将它重置为原来的状态。(这可以在自定义操纵器的析构函数中完成,或者使用作用域对象将格式保存在其构造函数中,并在其析构函数中还原。)查找ljust和rjust。当然,您可以将其包装在函数中,这样格式说明符在程序中只出现一次,并用逻辑语义标记。