Maybe someone in either of the camps can tell me whats going on here:
Python:
temp = int('%d%d' % (temp2, temp3)) / 10.0;
I'm working on parsing temperature data, and found a piece of python that I can't understand. What is going on here? Is python adding together two numbers here and casting them to int, and then divide by 10?
C# might look like:
temp = ((int)(temp2+temp3))/10;
But I am not sure what that % does? Data is jibberish so I don't know what is correct translation for that line in python to C#
In C# it looks like:
var temp = int.Parse(temp2.ToString() + temp3.ToString())/10f;
or:
var temp = Convert.ToInt32(string.Format("{0}{1}", temp2, temp3))/10f;
this is similar: What's the difference between %s and %d in Python string formatting?
name = 'marcog'
number = 42
print '%s %d' % (name, number)
will print marcog 42. Note that name is a string (%s) and number is an integer (%d for decimal).
See
http://docs.python.org/library/stdtypes.html#string-formatting-operations
for details.
So it seems like the "%" is just telling python to put the values on the right into the placeholders on the left.
from the documentation linked in the answer I quoted:
Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.
Would probably want to set up a python script and try it out, placing your own values into the variables.
Related
This question already has answers here:
What does $ mean before a string?
(11 answers)
Closed 6 years ago.
I have been looking over some C# exercises in a book and I ran across an example that stumped me. Straight from the book, the output line shows as:
Console.WriteLine($"\n\tYour result is {result}.");
The code works and the double result shows as expected. However, not understanding why the $ is there at the front of the string, I decided to remove it, and now the code outputs the name of the array {result} instead of the contents. The book doesn't explain why the $ is there, unfortunately.
I have been scouring the VB 2015 help and Google, regarding string formatting and Console.WriteLine overload methods. I am not seeing anything that explains why it is what it is. Any advice would be appreciated.
It's the new feature in C# 6 called Interpolated Strings.
The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.
For more details about this, please take a look at MSDN.
Now, think a little bit more about it. Why this feature is great?
For example, you have class Point:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
Create 2 instances:
var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };
Now, you want to output it to the screen. The 2 ways that you usually use:
Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");
As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format() to make it nicer:
Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));
This creates a new problem:
You have to maintain the number of arguments and index yourself. If the number of arguments and index are not the same, it will generate a runtime error.
For those reasons, we should use new feature:
Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");
The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
For the full post, please read this blog.
String Interpolation
is a concept that languages like Perl have had for quite a while, and
now we’ll get this ability in C# as well. In String Interpolation, we
simply prefix the string with a $ (much like we use the # for verbatim
strings). Then, we simply surround the expressions we want to
interpolate with curly braces (i.e. { and }):
It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.
A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.
Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.
{<interpolatedExpression>[,<alignment>][:<formatString>]}
Where:
interpolatedExpression - The expression that produces a result to be formatted
alignment - The constant expression whose value defines the minimum number of characters in the string representation of the
result of the interpolated expression. If positive, the string
representation is right-aligned; if negative, it's left-aligned.
formatString - A format string that is supported by the type of the expression result.
The following code example concatenates a string where an object, author as a part of the string interpolation.
string author = "Mohit";
string hello = $"Hello {author} !";
Console.WriteLine(hello); // Hello Mohit !
Read more on C#/.NET Little Wonders: String Interpolation in C# 6
I am in need of parsing an array or characters that is a fixed length but can have just about any combination of letter or number. My 50 digit array looks like this: NL1NAMEOFCO-B032144221111000100600000-A35499001
This array represents a vast combination of settings within our product. I need to extract all reference designators in the array. The first 3 characters represent a particular model NL1, the next 8 characters represent a company NAMEOFCO. The ‘-‘ will always be in the same location. The B (digit 13) represents some value, etc, etc. Also, some values are represented by 2 digits. Digits 20 & 21 (which store the value 22), represent some specific settings.
So by now you get the idea. I can parse the array and extract the values I need by using the following code:
String Company = ConfigCode[3].ToString() +
ConfigCode[4].ToString() +
ConfigCode[5].ToString() +
ConfigCode[6].ToString() +
ConfigCode[7].ToString() +
ConfigCode[8].ToString() +
ConfigCode[9].ToString() +
ConfigCode[10].ToString();
This works without any problems, but to me, there should be an easier way of doing this. I would have thought the following would work, but it does not.
String Company = ConfigCode[3..10].ToString();
Can someone explain to me why it doesn’t work and what would be a better way of extracting the information I need?
Thanks!
I believe that String.Substring method is what you're looking for. The signature for the overloaded method you're looking for is:
public string Substring(
int startIndex,
int length
)
The documentation for it is here: http://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx
For example, your Company name would be (going by the description of a character length of 8):
string CompanyName = configCode.Substring(3, 8);
Like mentioned before, you can use the Substring extension method like so:
String Company = ConfigCode.Substring(3, 8);
The square-bracket operators for strings, like in ConfigCode[3], actually return individual chars at that specific index. And C# isn't as pretty as other programming languages where stuff like array[3..10] actually gives you a portion of an array (or in this case, a string).
I'm not sure if "key value" is correct word for it as there are few formats I believe, what im talking about is http://pastebin.com/XJVx1dB5 this is format where 88 is Z etc. I hope im clear.
I have tried many things, but convert from string function of keys converter class is the only one that is remotely close. The problem is, it converts "x" to 88 as I wanted, however it fails to convert " " or "[" because it expects "SPACE"(string) and not a single space as char I believe.
I used it like this, maybe there is another(correct?) version of using it:
((int)kc.ConvertFromString(s))
So what I want to do is to get that chars of mine to code ones. How can I achieve this ?
Try something like:
var stringValue = " ";
var intValue = (int)stringValue[0];
A string is an 'array of chars' - so waht you need to do is get the char [in this case the first one] - and convert that to an int - in this case simply by casting.
If you want to do it with the enum, then you're going to have to write a manual system to convert " " to Keys.Space .
If you review your enum Keys carefully, you will see there is no value for [.
In fact, that character (on my keyboard) is reported as Oem4.
This code works:
var c = kc.ConvertFromString("Oem4");
However,
var c = kc.ConvertFromString("[");
Cannot work because [ is not a valid member of the enum you are converting from.
What do you want to do once you have converted the string? That may help guide a better answer to your question.
Progress databases allow for a Character[x] datatype. How can I write to a particular x using C# and ODBC?
Please do not answer unless you understand the what Character[x] means... it is not a string (array of chars), it is an array of strings (which are arrays of chars).
I figured it out. The documentation I have refers to a datatype of character[20], format x(24). character[x] (where x is a number), is like an array of strings. Format x(24) means each string in the array can be 24 characters long.
Essentially characters[20], format x(24) is a string that is 20 * 24 characters long with each "array element" separated with a semi-colon (;).
If column "options" is defined as character[20], x(24) then to populate it with strings from 1 to 20, one would merely write:
row.options = "1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20";
To populate it with all empty strings write:
row.options = ";;;;;;;;;;;;;;;;;;;";
Format x(24) means each string in the array can be 24 characters long.
Not quite accurate, the format is a DISPLAY format, which is used by a lot of the Progress routines when displaying / printing / exporting this field. All character fields, whether they have an extent or not, are stored on the DB as variable length string. So you could easily have up to about 32K worth of data in each of your 20 extents.
The Progress ODBC Driver Guide doesn't seem to mention that type at all?
Is there a C# equivalent for the VB.NET FormatNumber function?
I.e.:
JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);
In both C# and VB.NET you can use either the .ToString() function or the String.Format() method to format the text.
Using the .ToString() method your example could be written as:
JSArrayString += "^" + (inv.RRP * oCountry.ExchangeRate).ToString("#0.00")
Alternatively using the String.Format() it could written as:
JSArrayString = String.Format("{0}^{1:#0.00}",JSArrayString,(inv.RRP * oCountry.ExchangeRate))
In both of the above cases I have used custom formatting for the currency with # representing an optional place holder and 0 representing a 0 or value if one exists.
Other formatting characters can be used to help with formatting such as D2 for 2 decimal places or C to display as currency. In this case you would not want to use the C formatter as this would have inserted the currency symbol and further separators which were not required.
See "String.Format("{0}", "formatting string"};" or "String Format for Int" for more information and examples on how to use String.Format and the different formatting options.
Yes, the .ToString(string) methods.
For instance,
int number = 32;
string formatted = number.ToString("D4");
Console.WriteLine(formatted);
// Shows 0032
Note that in C# you don't use a number to specify a format, but you use a character or a sequence of characters.
Formatting numbers and dates in C# takes some minutes to learn, but once you understand the principle, you can quickly get anything you want from looking at the reference.
Here's a couple MSDN articles to get you started :
Standard Numeric Format Strings
Formatting Types
You can use string formatters to accomplish the same thing.
double MyNumber = inv.RRP * oCountry.ExchangeRate;
JSArrayString += "^" + MyNumber.ToString("#0.00");
While I would recommend using ToString in this case, always keep in mind you can use ANY VB.Net function or class from C# just by referencing Microsoft.VisalBasic.dll.