Nicely formatting output to console, specifying number of tabs
There is usually a %10s
kind of printf
scheme that formats nicely.
However, I have not used ruby at all, so you need to check that.
Yes, there is printf with formatting.
The above example should right align in a space of 10 chars.
You can format based on your widest field in the column.
printf ([port, ]format, arg...)
Prints arguments formatted according to the format like sprintf. If the first argument is the instance of the IO or its subclass, print redirected to that object. the default is the value of $stdout.
How to format strings using printf() to get equal length in the output
You can specify a width on string fields, e.g.
printf("%-20s", "initialization...");
And then whatever's printed with that field will be blank-padded to the width you indicate.
The -
left-justifies your text in that field.
Formatting console Output
Use %45s
to make a right justified field that is 45 characters long. And use %-45s
to make a left justified string. Also consider extracting your line printing into a function - that way you'll be able to change it easily in one place. Like this:
# fake setup
PASS = ["foo.exe", "bar.exe", "really_long_filename.exe"]
FAILED = ["failed.exe"]
types = ["32-bit", "64-bit", "64-bit"]
arch64 = '64'
arch32 = '32'
# your code
def print_row(filename, status, file_type):
print " %-45s %-15s %15s" % (filename, status, file_type)
print_row('FileName', 'Status', 'Binary Type')
for files in PASS:
log = types.pop()
if arch64 in log:
print_row(files, 'PASSED', '64-bit')
elif arch32 in log:
print_row(files, 'PASSED', '32-bit')
print"\n"
for files in FAILED:
print_row(files, 'FAILED', '')
print "\n\n"
Formatting C++ console output
You can write a procedure that always print the same number of characters to standard output.
Something like:
string StringPadding(string original, size_t charCount)
{
original.resize(charCount, ' ');
return original;
}
And then use like this in your program:
void list::displayByName(ostream& out) const
{
node *current_node = headByName;
out << StringPadding("Name", 30)
<< StringPadding("Location", 10)
<< StringPadding("Rating", 10)
<< StringPadding("Acre", 10) << endl;
out << StringPadding("----", 30)
<< StringPadding("--------", 10)
<< StringPadding("------", 10)
<< StringPadding("----", 10) << endl;
while ( current_node)
{
out << StringPadding(current_node->item.getName(), 30)
<< StringPadding(current_node->item.getLocation(), 10)
<< StringPadding(current_node->item.getRating(), 10)
<< StringPadding(current_node->item.getAcres(), 10)
<< endl;
current_node = current_node->nextByName;
}
}
Create nice column output in python
data = [['a', 'b', 'c'], ['Nicely Formatting Output to Console, Specifying Number of Tabsaa', 'b', 'c'], ['a', 'bb', 'c']]
col_width = max(len(word) for row in data for word in row) + 2 # padding
for row in data:
print "".join(word.ljust(col_width) for word in row)
a b c
Nicely Formatting Output to Console, Specifying Number of Tabsaa b c
a bb c
What this does is calculate the longest data entry to determine the column width, then use .ljust()
to add the necessary padding when printing out each column.
How to format string output, so that columns are evenly centered?
I'm also going with the "format" suggestion, but mine is a little different.
In your program, you're relying on your card's toString
. So make that formatted in a fixed length, and then you can use them anywhere and they will take up the same space.
public String toString() {
return String.format( "%5s of %-8s", rank, suit );
}
When you print this out, you'll have all your cards aligned on the "of" part, which I think is what you were going for in your first output column.
The "%5s" part right-aligns the rank in a field 5 characters wide, and the "%-8s" part left-aligns the suit in a field 8 characters wide (which means there are additional spaces to the right if the suit is shorter than 8 characters).
How to print a string at a fixed width?
EDIT 2013-12-11 - This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax.
You can use string formatting like this:
>>> print '%5s' % 'aa'
aa
>>> print '%5s' % 'aaa'
aaa
>>> print '%5s' % 'aaaa'
aaaa
>>> print '%5s' % 'aaaaa'
aaaaa
Basically:
- the
%
character informs python it will have to substitute something to a token - the
s
character informs python the token will be a string - the
5
(or whatever number you wish) informs python to pad the string with spaces up to 5 characters.
In your specific case a possible implementation could look like:
>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
... print 'value %3s - num of occurances = %d' % item # %d is the token of integers
...
value a - num of occurances = 1
value ab - num of occurances = 1
value abc - num of occurances = 1
SIDE NOTE: Just wondered if you are aware of the existence of the itertools
module. For example you could obtain a list of all your combinations in one line with:
>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']
and you could get the number of occurrences by using combinations
in conjunction with count()
.
How to use String.format() in Java to replicate tab \t?
consider using a negative number for your length specifier: %-20s
. For example:
public static void main(String[] args) {
String[] firstNames = {"Pete", "Jon", "Fred"};
String[] lastNames = {"Klein", "Jones", "Flinstone"};
String phoneNumber = "555-123-4567";
for (int i = 0; i < firstNames.length; i++) {
String foo = String.format("%-20s %s", lastNames[i] + ", " +
firstNames[i], phoneNumber);
System.out.println(foo);
}
}
returns
Klein, Pete 555-123-4567
Jones, Jon 555-123-4567
Flinstone, Fred 555-123-4567
Related Topics
What's the Difference Between Request.Remote_Ip and Request.Ip in Rails
How to List the Currently Available Objects in the Current Scope in Ruby
Read Input from Console in Ruby
When to Use Struct Instead of Hash in Ruby
Installing Ruby 1.9.1 on Ubuntu
Ruby: Is There an Opposite of Include? for Ruby Arrays
When We Import CSV Data, How Eliminate "Invalid Byte Sequence in Utf-8"
Cannot Access Local Sinatra Server from Another Computer on Same Network
Ruby Convert Array into Function Arguments
If String Is Empty Then Return Some Default Value
Find or Create Record Through Factory_Girl Association
Should I Define a Main Method in My Ruby Scripts
Parse Command Line Arguments in a Ruby Script
How to Handle Constants in Ruby When Using Rails