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)
Answer from Mark Ransom on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › c++ to python!
r/learnpython on Reddit: C++ to Python!
October 23, 2019 -

Hello, so ive made a programm in c++, and now im asked to make it in python, I have never programmed in python, so im looking for some help to translate it, would appreciate it.

The programm outputs a queen on a chessboard with and X and also puts an X on all fields where she can move, but all others are 0

This is my C++ programm:

#include <iostream>

#include <cmath>

#include <iomanip>

using namespace std;

int main() {

int x, number;  // x ir letter jeb burta apakš deklarācija

char letter;

cout << "Koordinatas burts: "; //Burta ievade

cin >> letter;

cout << "Koordinatas cipars: "; // cipara ievade

cin >> number;

cout << endl;

switch (letter) {           // pārvērš ievadītos burtus par cipariem, lai varētu ievadīt karalieni

case 'a': x = 1; break;

case 'b': x = 2; break;

case 'c': x = 3; break;

case 'd': x = 4; break;

case 'e': x = 5; break;

case 'f': x = 6; break;

case 'g': x = 7; break;

case 'h': x = 8; break;

}

for (int i = 1; i <= 8; i++) {         // Izveido laukumu

	for (int k = 1; k <= 8; k++) {     // Izveido laukumu

		if (x == k || 9 - number == i) // izvada karalieni un horizontālās un vertikālās līnijas

cout << setw(2) << 'X'; // setw uzstāda laukuma platumu, izvada X,kas ir karaliene un līnijas

else if (abs(number - 9 + i) == abs(x - k)) // Aprēķina diognāles

cout << setw(2) << 'X'; // izvada diognāles

else

cout << setw(2) << '0'; // izvada pārējo laukumu ar 0

	}

	cout << endl;

}

return 0;

}

Top answer
1 of 1
4

Well, I can already tell you won't even need to import anything. The readily-imported functions are enough.

You can mostly replace your cout-cin pairs with input, and other couts with print. Example:

int foo;

std::cout << "Your age: ";
std::cin >> foo;

is equivalent to

foo = int(input("Your age: "))

input always returns an unicode string in Python 3. We can use int to parse it into an integer. No need to worry about overflows, because Python uses arbitrary-precision integers. Think long long, but bigger.

Next, the switch-case. Python doesn't have them, but dictionaries are the next best thing!

switch = {key: value for value, key in enumerate("abcdef", 1)} # dict comprehension that populates a dictionary on the spot
num = switch.get(
    'c',
    0 # default case, you can omit it
)
print(num == 3) # prints True

EDIT: Finally, for-loops. Python doesn't have the C-style for-loop, only the C++11-style iterative for-loop. Prefer iterative style whenever possible.

You can emulate a C-style loop by looping over range:

for i in range(0, 10, 1): # start, stop, step, 0-9 in this case
    print(i)

However, since this is a common operation, the start and step default to 0 and 1, respectively, so you can just give the function the endpoint:

for i in range(10):
    print(i)

However, when you need both indexes and values, use enumerate:

stuff = [2**i for i in range(42)] # list comprehension, creates a list on the spot

for idx, val in enumerate(stuff):
    print(f"value {val} at index {idx}") # f-strings make string formatting easy
🌐
Sololearn
sololearn.com › en › Discuss › 1256551 › what-is-equivalent-to-setw-in-c-to-python
What is equivalent to setw() in c to python?
May 4, 2018 - Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
🌐
HotExamples
python.hotexamples.com › examples › color › - › setW › python-setw-function-examples.html
Python setW Examples, color.setW Python Examples - HotExamples
color.setB(light.ser, red, green, blue) elif request['light'][0].lower() == 'ab': color.setA(light.ser, red, green, blue) color.setB(light.ser, red, green, blue) elif 'color' in request: color=request['color'][0] if request['light'][0].lower() == 'a': light.colors[color].setA() elif request['light'][0].lower() == 'b': light.colors[color].setB() elif request['light'][0].lower() == 'ab': light.colors[color].setA() light.colors[color].setB() elif 'brightness' in request: color.setW(light.ser, int(request['brightness'][0])) elif 'off' in request: color.setA(light.ser, 0, 0, 0) color.setB(light.ser, 0, 0, 0) color.setW(light.ser, 0) elif 'on' in request: color.setA(light.ser, 255, 15, 0) color.setB(light.ser, 255, 15, 0) color.setW(light.ser, 255) print '<h1><a href="index.py?off">All Lights off</a></h1>' print '<h2>Enter your own RGB color or pick from the list.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › print-pattern-using-only-one-loop
Print pattern using only one loop | Set 1 (Using setw) - GeeksforGeeks
July 23, 2025 - DSA Python · Last Updated : 23 ... **** *****Input : 6 Output : * ** *** **** ***** ****** setw(n) Creates n columns and fills these n columns from right....
🌐
Blogger
backgroundcode121.blogspot.com › 2013 › 09 › c-setfill-and-setw-python-equivalent.html
c++ - setfill and setw python equivalent? -
December 5, 2017 - there's no direct equivalent, can convert each value want display format function. see https://docs.python.org/2/library/string.html#format-specification-mini-language format specification.
🌐
YouTube
youtube.com › hey delphi
C++ : setfill and setw python equivalent? - YouTube
C++ : setfill and setw python equivalent?To Access My Live Chat Page, On Google, Search for "hows tech developer connect"As promised, I have a secret feature...
Published: May 1, 2023
Views: 35
🌐
YouTube
youtube.com › d.k al
Using Setw - YouTube
A quick demo of how to use C++ setw manipulator to format a table.
Published: March 17, 2019
Views: 8K
Find elsewhere
🌐
OneCompiler
onecompiler.com › python › 3z27aw7vq
Python Online Compiler & Interpreter
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab.
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › stdsetbase-stdsetw-stdsetfill-in-cpp
std::setbase, std::setw , std::setfill in C++ - GeeksforGeeks
April 2, 2024 - std::setw : Set field width; Sets the field width to be used on output operations. Behaves as if member width were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input ...
🌐
GeeksforGeeks
geeksforgeeks.org › iomanip-setw-function-in-c-with-examples
iomanip setw() function in C++ with Examples - GeeksforGeeks
July 29, 2021 - The setw() method of iomanip library in C++ is used to set the ios library field width based on the width specified as the parameter to this method.
🌐
TutorialsPoint
tutorialspoint.com › cpp_standard_library › cpp_setw.htm
C++ iomanip Library - setw Function
The C++ function std::setw behaves as if member width were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams).
🌐
Medium
medium.com › @ryan_forrester_ › using-setw-in-c-practical-guide-2ce6ce50fc7a
Using setw in C++: Practical Guide | by ryan | Medium
October 4, 2024 - Enter `setw`, a handy tool that can save you hours of frustration. Short for “set width,” `setw` is an I/O manipulator that helps you control the width of the output field.
🌐
Reddit
reddit.com › r/cpp_questions › question about formatting output using setw()
r/cpp_questions on Reddit: Question about formatting output using setw()
June 8, 2024 -

I wrote a program for a class that is a loan calculator. For the outputted table I originally tried using \t for formatting, but that didn't work so im using setw() instead. Whenever the interest gets down to the double or single digits, the balance column is thrown off. Apologies for any style issues I'm still learning, thanks!

include <iostream>

include <cmath>

include <iomanip>

using namespace std;

int main()

{

//setprecision for monthlyInt calculation, setting variables

cout << fixed << showpoint << setprecision(6);

double loanAmount, apr, loanTerm;

double interestTotal = 0.0;

int month = 0;

//input for calculations

cout << "Enter the loan amount: ";

cin >> loanAmount;

cout << "Enter the annual percentage rate: ";

cin >> apr;

cout << "Enter the loan term in months: ";

cin >> loanTerm;

cout << endl;

//calculates based on 12th root of annual interest

double monthlyInt = pow(1 + (apr / 100.0), (1.0 / 12.0)) - 1;

//calculates monthly payments

double monthlyPayments = loanAmount * monthlyInt * (pow((1.0 + monthlyInt), (loanTerm))) / (pow((1.0 + monthlyInt), (loanTerm)) - 1.0);

//defining balance remaining before loop

double balanceLeft = loanAmount;

//header for table

cout << "Month" << setw (10) << "Payment" << setw(14) << "Principal" << setw(11) << "Interest" << setw(12) << "Balance\n";

//loop for decrementing until balance left is 0,

while (balanceLeft > 0) {

cout << fixed << showpoint << setprecision(2);

double interest = balanceLeft * monthlyInt;

double principal = monthlyPayments - interest;

balanceLeft = balanceLeft - principal;

interestTotal = interestTotal + interest;

month++;

cout << month << "\t" << "$" << monthlyPayments << right << setw(6) << "$"

<< principal << right << setw(6) << "$" << interest << right << setw(6)

<< "$" << balanceLeft << "\n";

}

//outputs totals

cout << endl;

cout << "Payment every month is $" << monthlyPayments << endl;

cout << "Total payments is $" << monthlyPayments * loanTerm << endl;

cout << "Total interest is $" << interestTotal << endl;

return 0;

}

🌐
W3Schools
w3schools.com › python › python_sets.asp
Python Sets
Sets are used to store multiple items in a single variable.
🌐
Programiz
programiz.com › python-programming › set
Python Set (With Examples)
In Python, we create sets by placing all the elements inside curly braces {}, separated by commas.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 289310 › use-setw-in-a-string
c++ - Use setw in a string [SOLVED] | DaniWeb
setw and the other iomanipulators work on streams, not on strings. To end up with a std::string, format into a stream that writes to memory, then extract its buffer. The standard way is to use std::ostringstream.
🌐
cppreference.com
en.cppreference.com › cpp › io › manip › setw
std::setw - cppreference.com
July 23, 2023 - Some operations reset the width to zero (see below), so std::setw may need to be repeatedly called to set the width for multiple operations.