10

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?

4
  • 1
    Didn't look very hard did you... '<any_char>'*n returns any_char n times. "%x"%myVar formats myVar as a hex. Commented Jun 11, 2014 at 14:59
  • 1
    But who'd write anything like this to begin with? If myVar has a semantic such that it requires such formatting, you'd write a single manipulator which does that, to be used with all variables which have that semantics. (In Python, the only way I can think of off hand to to that is to write a function which does the conversion, using the desired formatting, and returns a string.) Commented Jun 11, 2014 at 15:20
  • 1
    Also, of course: you wouldn't return the format to std::dec; you'd reset it to whatever it was before you changed it. (This can be done in the destructor of a custom manipulator, or by use of a scoped object which saves the format in its constructor, and restores it in its destructor.) Commented Jun 11, 2014 at 15:23
  • Look up ljust and rjust. Commented Jun 4, 2020 at 12:24

3 Answers 3

5

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

And of course, you'd wrap this in a function, so that the format specifier only occurs once in your program, and is labeled with the logical semantics.
4

I used '{:>n}'.format(nbr).

Example:

In [13]: '{:>2}'.format(1) Out[13]: ' 1' In [14]: '{:>2}'.format(10) Out[14]: '10' 

Comments

0

In order to get the same result you can use this:

res = '{0>2}'.format(x) 
  • '0' is the character used to fill in the blank spaces.
  • '>' means 'x' will be aligned to the right.
  • '2' defines the total width.

The output using the previous code and printing the result being x = 2 will be:

02 

You can also use this format in strings not just for print.

1 Comment

This is already covered in this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.