How to replace the list of decimal numbers in a string with another list of decimal numbers? - python-re

I need to replace the list of decimal numbers in a string with another list of decimal numbers. The following is a first try, that changes all decimal numbers with the same decimal number:
>>> re.sub (r"[-+]?\d*\.\d+f?", "1.0", "hello 1.2 3.4")
'hello 1.0 1.0'
I need something like my_replace below:
>>> my_replace (r"[-+]?\d*\.\d+f?", [1.0, 2.0], "hello 1.2 3.4")
'hello 1.0 2.0'
How can i implement my_replace with python's re module?

I don't think that you can use a list as replacement variables and iterate over them. So it can't handle unhashable objects (this is what python is complaining about). But it wouln'd be able to handle numerics as well (so it would need a list of strings but this is obviously hypothetical xD)
I would just loop over the string and compy everything that is not a decimal number to a new string and replacing the decimal numbers found.
text = "hello 1.2 3.4 don't replace an integer: 9 but this decimal number is too much: 0.0 (so use last value!)"
new_numbers = [42, 3.1415926535]
new_text = ''
idx_last = 0
for i, tx in enumerate(re.finditer(r'[-+]?\d*\.\d+f?', text)):
# add text before the number
new_text += tx.string[idx_last:tx.start()]
# add new number (but ensure that your are not overflowing the list of new numbers
new_text += str(new_numbers[min([i, len(new_numbers) - 1])])
# update text index
idx_last = tx.end()
# update remaining part of the text
new_text += text[idx_last:]
"hello 42 3.1415926535 don't replace an integer: 9 but this decimal number is too much: 3.1415926535 (so use last value!)"
Wrap it to a function and you have your my_replace() =)

Related

Dividing the input in python

I'm doing a project where I need to insert coordinates in the console to return a place in a grid. My grid is 10*10 and has numbers in the rows and Letters in the columns.
I want to be able to input something like A1 and for it to be interpreted as "column1, row1"
So far I have got:
def get_coor():
user_input = input("Please enter coordinates (row,col) ? ")
coor = user_input.split(" ")
return coor
But I'm only able to split if I have a space. Is there any other function to help me in this situation?
Strings are iterable in Python.
If you write:
user_input = input("Please enter coordinates (row,col)?")
<input A1>
Then user_input[0] will be A and user_input[1] will be 1.
Therefore, no need for the split :)
Split is used precisely for the use case when there is a space: it returns a list of all the strings between the occurrences of the character given as an argument (in your case a space).

FormatNumber replacing number with 0

Not understanding this:
Number returned from DataReader: 185549633.66000035
We have a requirement to maintain the number of decimal places per a User Choice.
For example: maintain 7 places.
We are using:
FormatNumber(dr.Item("Field"), 7, TriState.false, , TriState.True)
The result is: 185,549,633.6600000.
We would like to maintain the 3 (or 35) at the end.
When subtracting two numbers from the resulting query we are getting a delta but trying to show these two numbers out to 6,7,8 digits is not working thus indicating a false delta to the user.
Any advice would be appreciated.
Based on my testing, you must be working with Double values rather than Decimal. Not surprisingly, the solution to your problem can be found in the documentation.
For a start, you should not be using FormatNumber. We're not in VB6 anymore ToTo. To format a number in VB.NET, call ToString on that number. I tested this:
Dim dbl = 185549633.66000035R
Dim dec = 185549633.66000035D
Dim dblString = dbl.ToString("n7")
Dim decString = dec.ToString("n7")
Console.WriteLine(dblString)
Console.WriteLine(decString)
and I saw the behaviour you describe, i.e. the output was:
185,549,633.6600000
185,549,633.6600004
I read the documentation for the Double.ToString method (note that FormatNumber would be calling ToString internally) and this is what it says:
By default, the return value only contains 15 digits of precision although a maximum of 17 digits is maintained internally. If the value of this instance has greater than 15 digits, ToString returns PositiveInfinitySymbol or NegativeInfinitySymbol instead of the expected number. If you require more precision, specify format with the "G17" format specification, which always returns 17 digits of precision, or "R", which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision.
I then tested this:
Dim dbl = 185549633.66000035R
Dim dblString16 = dbl.ToString("G16")
Dim dblString17 = dbl.ToString("G17")
Console.WriteLine(dblString16)
Console.WriteLine(dblString17)
and the result was:
185549633.6600004
185549633.66000035

Converting binary to base 4

What I hope to achieve:
I want to convert text to DNA (which is a base 4 system, "a,G,T,c")
How I plan to do it:
Convert text string to binary,
Dim BinaryConvert As String = ""
For Each C As Char In Textbox1.Text
Dim s As String = System.Convert.ToString(AscW(C), 2).PadLeft(8, "0")
BinaryConvert &= s
Next
Textbox1.Text = BinaryConvert '//Changes the textbox1.Text into binary form
Then convert binary to base 4 via Pseudocode solution:
if (length of binary String is an odd number) add a zero to the front (leftmost position) of the String.
Create an empty String to add translated digits to.
While the original String of binary is not empty {
Translate the first two digits only of the binary String into a base-4 digit, and add this digit to the end (rightmost) index of the new String.
After this, remove the same two digits from the binary string and repeat if it is not empty.
}
The idea behind converting binary to DNA is simply setting G and T equal to one, with c and a equal to zero (G=T=1, a=c=0).
So all I have to do is convert the string to binary first, and then into base 4, in order to convert text to genetic code. Could you please help me write the code to convert binary to base 4.
Thank you for the help!
Converting to base 4 from base 2 is pretty simple. Since 4 itself is the 2nd power of 2, this means you can simply combine two bits to create one base 4 place (2 bits can represent 4 possible values, while 1 base 4 place can also represent 4 possible values). For example:
11100100 (base 2) = 3210 (base 4)

How to write number with sign on the left and thousands separator point

I am holding the number in character format in abap. Because I have to take the minus from right to left. So I have to put the number to character and shift or using function 'CLOI_PUT_SIGN_IN_FRONT' I'm moving minus character to left.
But after assigning number to character it doesn't hold the points. I mean my number is;
1.432- (as integer)
-1432 (as character)
I want;
-1.432 (as character)
is there a shortcut for this or should I append some string operations.
Edit:
Here is what I'm doing now.
data: mustbak_t(10) TYPE c,
mustbak like zsomething-menge.
select single menge from zsomething into mustbak where something eq something.
mustbak_t = mustbak.
CALL FUNCTION 'CLOI_PUT_SIGN_IN_FRONT'
CHANGING
VALUE = mustbak_t.
write: mustbak_t.
If you're on a recent release, you could use string templates - you'll have to add some black magic to use a country that confoirms to your decimal settings, though:
DATA: l_country TYPE t005x-land,
l_text TYPE c LENGTH 15,
l_num TYPE p LENGTH 6.
SELECT SINGLE land
INTO l_country
FROM t005x
WHERE xdezp = space.
l_num = '-123456'.
l_text = |{ l_num COUNTRY = l_country }|.
WRITE: / l_text.
In this case, you need a country code to pass to the COUNTRY parameter as described in the format options. The values of the individual fields, namely T005X-XDEZP are described in detail in the country-specific formats.
tl;dr = Find any country where they use "." as a thousands separator and "," as a decimal separator and use that country settings to format the number.
You could also use classic formatting templates, but they are hard to handle unless you have a fixed-length output value:
DATA: l_text TYPE c LENGTH 15,
l_num TYPE p LENGTH 6 DECIMALS 2.
l_num = '-1234.56'.
WRITE l_num TO l_text USING EDIT MASK 'RRV________.__'.
CONDENSE l_text NO-GAPS.
WRITE: / l_text.
Here's another way, which i finally got working:
DATA: characters(18) TYPE c,
ints TYPE i VALUE -222333444.
WRITE ints TO characters. "This is it... nothing more to say.
CALL FUNCTION 'CLOI_PUT_SIGN_IN_FRONT'
CHANGING
value = characters.
WRITE characters.
Since integers are automatically printed with the thousands separator, you can simply output them to a char data object directly using WRITE TO with no aditions..... lol
DATA: currency TYPE cdcurr,
characters(18) TYPE c,
ints TYPE i VALUE -200000.
currency = ints.
WRITE currency TO characters CURRENCY 'USD' DECIMALS 0.
CALL FUNCTION 'CLOI_PUT_SIGN_IN_FRONT'
CHANGING
value = characters.
.
WRITE: / 'example',characters.
This prints your integer as specified. Must be apparently converted to a currency during the process.

vb.net what is a good way of displaying a decimal with a given maximum length

I am writing a custom totaling method for a grid view. I am totaling fairly large numbers so I'd like to use a decimal to get the total. The problem is I need to control the maximum length of the total number. To solve this problem I started using float but it doesn't seem to support large enough numbers, I get this in the totals column(1.551538E+07). So is there some formating string I can use in .ToString() to guarentee that I never get more then X characters in the total field? Keep in mind I'm totaling integers and decimals.
If you're fine with all numbers displaying in scientific notation, you could go with "E[numberOfDecimalPlaces]" as your format string.
For example, if you want to cap your strings at, say, 12 characters, then, accounting for the one character for the decimal point and five characters needed to display the exponential part, you could do:
Function FormatDecimal(ByVal value As Decimal) As String
If value >= 0D Then
Return value.ToString("E5")
Else
' negative sign eats up another character '
Return value.ToString("E4")
End If
End Function
Here's a simple demo of this function:
Dim d(5) As Decimal
d(0) = 1.203D
d(1) = 0D
d(2) = 1231234789.432412341239873D
d(3) = 33.3218403820498320498320498234D
d(4) = -0.314453908342094D
d(5) = 000032131231285432940D
For Each value As Decimal in d
Console.WriteLine(FormatDecimal(value))
Next
Output:
1.20300E+000
0.00000E+000
1.23123E+009
3.33218E+001
-3.1445E-001
3.21312E+016
You could use Decimal.Round, but I don't understand the exact question, it sounds like you're saying that if the total adds up to 12345.67, you might only want to show 4 digits and would then show 2345 or do you just mean that you want to remove the decimals?