Convert int to binary string in Python
Python’s string format method can take a format spec. >>> “{0:b}”.format(37) ‘100101’ Format spec docs for Python 2 Format spec docs for Python 3
Python’s string format method can take a format spec. >>> “{0:b}”.format(37) ‘100101’ Format spec docs for Python 2 Format spec docs for Python 3
Late to the party, but you can simply use strtr to “translate characters or replace substrings” <?php $hours = 2; $minutes = 24; $seconds = 35; // Option 1: Replacing %variable echo strtr( ‘Last time logged in was %hours hours, %minutes minutes, %seconds seconds ago’, [ ‘%hours’ => $hours, ‘%minutes’ => $minutes, ‘%seconds’ => $seconds … Read more
No, but this extension method will do it static string FormatFromDictionary(this string formatString, Dictionary<string, string> valueDict) { int i = 0; StringBuilder newFormatString = new StringBuilder(formatString); Dictionary<string, int> keyToInt = new Dictionary<string,int>(); foreach (var tuple in valueDict) { newFormatString = newFormatString.Replace(“{” + tuple.Key + “}”, “{” + i.ToString() + “}”); keyToInt.Add(tuple.Key, i); i++; } return … Read more
Use the P format string. This will vary by culture: String.Format(“Value: {0:P2}.”, 0.8526) // formats as 85.26 % (varies by culture)
NOTE: This answer was written when .NET 2.0 was the current version. This may no longer apply to later versions. String.Format uses a StringBuilder internally: public static string Format(IFormatProvider provider, string format, params object[] args) { if ((format == null) || (args == null)) { throw new ArgumentNullException((format == null) ? “format” : “args”); } … Read more
I’d suggest that it is better practice to use String.format(). The main reason is that String.format() can be more easily localised with text loaded from resource files whereas concatenation can’t be localised without producing a new executable with different code for each language. If you plan on your app being localisable you should also get … Read more
I can see a number of reasons: Readability string s = string.Format(“Hey, {0} it is the {1}st day of {2}. I feel {3}!”, _name, _day, _month, _feeling); vs: string s = “Hey,” + _name + ” it is the ” + _day + “st day of ” + _month + “. I feel ” + … Read more
The source code for ASP.NET AJAX is available for your reference, so you can pick through it and include the parts you want to continue using into a separate JS file. Or, you can port them to jQuery. Here is the format function… String.format = function() { var s = arguments[0]; for (var i = … Read more
I’m amazed that so many people immediately want to find the code that executes the fastest. If ONE MILLION iterations STILL take less than a second to process, is this going to be in ANY WAY noticeable to the end user? Not very likely. Premature optimization = FAIL. I’d go with the String.Format option, only … Read more
Python int to binary string?