pythonformatting

What is the equivalent to setfill and setw of C++ in Python?


I am currently porting some C++ code to Python but didn't find out how to translate this:

std::cout << std::setfill('0') << std::setw(2) << std::hex << myVar << std::dec << " "

How do I translate std::setfill('0') and std::setw(2) to Python?


Solution

  • There's no direct equivalent, but you can convert each value you want to display with the format function. See https://docs.python.org/2/library/string.html#format-specification-mini-language for the format specification.

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