string-formatting

Python: String Formatter Align center

馋奶兔 提交于 2019-11-29 06:53:31
print('%24s' % "MyString") # prints right aligned print('%-24s' % "MyString") # prints left aligned How do I print it in the center? Is there a quick way to do this? I don't want the text to be in the center of my screen. I want it to be in the center of that 24 spaces. If I have to do it manually, what is the math behind adding the same no. of spaces before and after the text? Use the new-style format method instead of the old-style % operator, which doesn't have the centering functionality: print('{:^24s}'.format("MyString")) You can use str.center() method. In your case, it will be:

A faster alternative to DecimalFormat.format()?

馋奶兔 提交于 2019-11-29 06:14:33
问题 In order to improve its performance, I have been profiling one of my applications with the VisualVM sampler, using the minimum sampling period of 20ms. According to the profiler, the main thread spends almost a quarter of its CPU time in the DecimalFormat.format() method. I am using DecimalFormat.format() with the 0.000000 pattern to "convert" double numbers to a string representation with exactly six decimal digits. I know that this method is relatively expensive and it is called a lot of

Formatting Floating Point Numbers

杀马特。学长 韩版系。学妹 提交于 2019-11-29 06:12:31
I have a variable of type double , I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros... eg. I need 2.5 // not 2.500 2 // not 2.000 1.375 // exactly till 3 decimals 2.12 // not 2.120 I tried using DecimalFormatter , Am i doing it wrong? DecimalFormat myFormatter = new DecimalFormat("0.000"); myFormatter.setDecimalSeparatorAlwaysShown(false); Thanks. :) Try the pattern "0.###" instead of "0.000" : import java.text.DecimalFormat; public class Main { public static void main(String[] args) { DecimalFormat df = new DecimalFormat("0.###"); double[] tests = {2

Python string format: When to use !s conversion flag

心不动则不痛 提交于 2019-11-29 05:58:59
What's the difference between these 2 string format statements in Python: '{0}'.format(a) '{0!s}'.format(a) Both have the same output if a is an integer, list or dictionary. Is the first one {0} doing an implicit str() call? Source PS: keywords: exclamation / bang "!s" formatting It is mentioned in the documentation: The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of

Printing boolean values True/False with the format() method in Python

浪子不回头ぞ 提交于 2019-11-29 05:48:10
问题 I was trying to print a truth table for Boolean expressions. While doing this, I stumbled upon the following: >>> format(True, "") # shows True in a string representation, same as str(True) 'True' >>> format(True, "^") # centers True in the middle of the output string '1' As soon as I specify a format specifier, format() converts True to 1 . I know that bool is a subclass of int , so that True evaluates to 1 : >>> format(True, "d") # shows True in a decimal format '1' But why does using the

C# String Format for hours and minutes from decimal

ぃ、小莉子 提交于 2019-11-29 05:47:23
Is there a simple string format that will take a decimal representing hours and fractions of hours and show it as hours and minutes? For example : 5.5 formatted to display 5 hrs 30 minutes. I am happy to write the code myself, however would prefer to use existing functionality if it is available decimal t = 5.5M; Console.WriteLine(TimeSpan.FromHours((double)t).ToString()); That'll give you "05:30:00" which is pretty close. You could then format that to your desired result: var ts = TimeSpan.FromHours((double)t); Console.WriteLine("{0} hrs {1} minutes", ts.Hours, ts.Minutes); Note that there's

StringFormat is ignored

混江龙づ霸主 提交于 2019-11-29 05:31:19
This is my binding (shortened, Command-Property is also bound) <MenuItem Header="Key" CommandParameter="{Binding StringFormat='Key: {0}', Path=PlacementTarget.Tag, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/> The Tag-Property of ContectMenu's PlacementTarget is a String like "Short.Plural" What i expect to receive in the Command-Handler is: Key: Short.Plural But what i acutally receive is: Short.Plural Label does not use StringFormat but ContentStringFormat. Use it this way: <TextBlock x:Name="textBlock" Text="Base Text"/> <Label Content="{Binding Path=Text, ElementName

Why does .Net use a rounding algorithm in String.Format that is inconsistent with the default Math.Round() algorithm?

心已入冬 提交于 2019-11-29 05:11:15
问题 I've noticed the following inconsistency in C#/.NET. I was wondering why it is so. Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.04, Math.Round(1.04, 1)); Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.05, Math.Round(1.05, 1)); Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.06, Math.Round(1.06, 1)); Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.14, Math.Round(1.14, 1)); Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.15, Math.Round(1.15, 1)); Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.16

str.format() raises KeyError

半城伤御伤魂 提交于 2019-11-29 04:20:29
问题 The following code raises a KeyError exception: addr_list_formatted = [] addr_list_idx = 0 for addr in addr_list: # addr_list is a list addr_list_idx = addr_list_idx + 1 addr_list_formatted.append(""" "{0}" { "gamedir" "str" "address" "{1}" } """.format(addr_list_idx, addr)) Why? I am using Python 3.1. 回答1: The problem is those { and } characters you have there that don't specify a key for formatting. You need to double them up, so change your code to: addr_list_formatted.append(""" "{0}" {{

How do I format a double to a string and only show decimal digits when necessary?

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-29 04:02:30
I have code like: lblFranshizShowInvwNoskhehEdit.Text = string.Format("{0:n}", (double)(int.Parse(drDarman["FranshizDarsad"].ToString()) * Convert.ToInt64(RadNumerictxtPayInvwNoskhehEdit.Text)) / 100); But {0:n0} string format forces the label's text to not have decimal digits and {0:n} string format forces the label's text to have 2 decimal digits (default). In my scenario I just want decimal digits when necessary / without rounding them / how can I do that? You can just do: string.Format("{0}", yourDouble); It will include only digits when necessary. If you want other examples of formatting