How to remove comma from string 1,398.90 using groovy - groovy

I am not able to remove comma from string 1,398.90 using groovy
def liveprice = '1,398.90';
def liveprice2 = liveprice.replaceAll(',', '')

I would really avoid using regular expressions with numbers
Especially numbers that look like money 💰
You can use DecimalFormat to read that String into a BigDecimal (so you keep precision)
import java.text.*
BigDecimal result = DecimalFormat.instance.with {
parseBigDecimal = true
parse('1,398.90')
}

As mentioned by #daggett, your code works fine. Another alternative way besides regex or replace:
'1,39,9,,,,.90'.split(",").join()
// outputs: 1399.90

Related

Get number from string in Python

I have a string, I have to get digits only from that string.
url = "www.mylocalurl.com/edit/1987"
Now from that string, I need to get 1987 only.
I have been trying this approach,
id = [int(i) for i in url.split() if i.isdigit()]
But I am getting [] list only.
You can use regex and get the digit alone in the list.
import re
url = "www.mylocalurl.com/edit/1987"
digit = re.findall(r'\d+', url)
output:
['1987']
Replace all non-digits with blank (effectively "deleting" them):
import re
num = re.sub('\D', '', url)
See live demo.
You aren't getting anything because by default the .split() method splits a sentence up where there are spaces. Since you are trying to split a hyperlink that has no spaces, it is not splitting anything up. What you can do is called a capture using regex. For example:
import re
url = "www.mylocalurl.com/edit/1987"
regex = r'(\d+)'
numbers = re.search(regex, url)
captured = numbers.groups()[0]
If you do not what what regular expressions are, the code is basically saying. Using the regex string defined as r'(\d+)' which basically means capture any digits, search through the url. Then in the captured we have the first captured group which is 1987.
If you don't want to use this, then you can use your .split() method but this time provide a split using / as the separator. For example `url.split('/').

An Elegant Solution to Python's Multiline String?

I was trying to log a completion of a scheduled event I set to run on Django. I was trying my very best to make my code look presentable, So instead of putting the string into a single line, I have used a multiline string to output to the logger within a Command Management class method. The example as code shown:
# the usual imports...
# ....
import textwrap
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **kwargs):
# some codes here
# ....
final_statement = f'''\
this is the final statements \
with multiline string to have \
a neater code.'''
dedented_text = textwrap.dedent(final_statment)
logger.info(dedent.replace(' ',''))
I have tried a few methods I found, however, most quick and easy methods still left a big chunk of spaces on the terminal. As shown here:
this is the final statement with multiline string to have a neater code.
So I have come up with a creative solution to solve my problem. By using.
dedent.replace(' ','')
Making sure to replace two spaces with no space in order not to get rid of the normal spaces between words. Which finally produced:
this is the final statement with multiline string to have a neater code.
Is this an elegant solution or did I missed something on the internet?
You could use regex to simply remove all white space after a newline. Additionally, wrapping it into a function leads to less repetitive code, so let's do that.
import re
def single_line(string):
return re.sub("\n\s+", "", string)
final_statement = single_line(f'''
this is the final statements
with multiline string to have
a neater code.''')
print(final_statement)
Alternatively, if you wish to avoid this particular problem (and don't mine the developmental overhead), you could store them inside a file, like JSON so you can quickly edit prompts while keeping your code clean.
Thanks to Neil's suggestion, I have come out with a more elegant solution. By creating a function to replace the two spaces with none.
def single_line(string):
return string.replace(' ','')
final_statement = '''\
this is a much neater
final statement
to present my code
'''
print(single_line(final_statement)
As improvised from Neil's solution, I have cut down the regex import. That's one line less of code!
Also, making it a function improves on readability as the whole print statement just read like English. "Print single line final statement"
Any better idea?
The issue with both Neil’s and Wong Siwei’s answers is they don’t work if your multiline string contains lines more indented than others:
my_string = """\
this is my
string and
it has various
identation
levels"""
What you want in the case above is to remove the two-spaces indentation, not every space at the beginning of a line.
The solution below should work in all cases:
import re
def dedent(s):
indent_level = None
for m in re.finditer(r"^ +", s):
line_indent_level = len(m.group())
if indent_level is None or indent_level > line_indent_level:
indent_level = line_indent_level
if not indent_level:
return s
return re.sub(r"(?:^|\n) {%s}" % indent_level, "", s)
It first scans the whole string to find the lowest indentation level then uses that information to dedent all lines of it.
If you only care about making your code easier to read, you may instead use C-like strings "concatenation":
my_string = (
"this is my string"
" and I write it on"
" multiple lines"
)
print(repr(my_string))
# => "this is my string and I write it on multiple lines"
You may also want to make it explicit with +s:
my_string = "this is my string" + \
" and I write it on" + \
" multiple lines"

Python How to split a string when find the first numeric char

This is my string:
"Somestring8/9/0"
I need to get something like this:
['Somestring','8/9/0']
The moment I find a numeric char, I need to split the string to get:
'8/9/0'
This my code:
stringSample = "GigabitEthernet8/9/0"
print re.findall(r'(\w+?)(\d+)', stringSample)[0]
('GigabitEthernet', '8')
But I'm getting this result
What am I doing wrong?
I appreciate your help!!
Your second regex group accepts only digits. Allow it to include forward slashes too.
stringSample = "GigabitEthernet8/9/0"
print re.findall(r'(\w+?)([\d/]+)', stringSample)[0]
# ('GigabitEthernet', '8/9/0')
Try Using the re.split method to split your string in two, passing the maxsplit parameter
re.split('(\w+?)([\d/]+)', stringSample, 1)

Scala - proper way to print a string to file

What is the proper way to print a string - and only the string - to file? When I try to do it the standard way known to me, i.e:
def printToFile(o:Object,n:String) = try{
val pathToOutput = "..\\some\\parent\\directory\\"
val path = Paths.get(pathToOutput + n)
val b = new ByteArrayOutputStream()
val os = new ObjectOutputStream(b)
os.writeObject(o)
Files.write(path, b.toByteArray,
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING)
}catch{
case _:Exception => println("failed to write")
}
it always seems to prepend
’ NUL ENQtSTXT
Where the part after ENQt seems to vary.
(Doesn't matter if I declare oan Object or a String.)
This is very annoying because I want to print a couple of .dot-Strings (Graphviz) in order to then batch-process the resulting .dot-files to .pdf-files. The prepended nonsense, however, forces me to open each .dot-file and remove it manually - which kind of defeats the purpose of batch-processing them.
This has nothing to do with Scala specifically, it's the way the Java Standard Library works. When you do a writeObject you are writing a Serialized representation of the Object, together with a bunch of additional bytes the JVM can use to re-create that object. If you know the object is a String, then strong-type it (i.e., use printToFile(o:String,n:String) and you can use Files.write(path, o.getBytes, .... Otherwise you could use o.toString.getBytes.
Generally in JVM, if you want to write characters and not bytes, you should prefer *Writer over *OutputStream. In this case (assuming you have a File where you want to write and a String which you want to write):
val writer = new BufferedWriter(new FileWriter(file))
try {
writer.write(string)
} finally {
writer.close()
}
Or with the character-oriented overload of Files.write:
Files.write(path, Collections.singletonList(string), ...)

Decode HTML Entities to UTF-8 in groovy

I am not sure how to decode the html entities to UTF-8 in groovy?
"& quot;"
should be decoded as " in groovy program.
Can anyone help me with this solution?
For semantic correctness: What you actually want to do is not to change the encoding, but to parse the markup.
(I may go to the engineers hell for giving you the following solution, but you might actually do this if you insist on staying with the Groovy-essentials to solve your problem.)
You can surround your string or character with a valid html-tag and utilize the XMLSlurper to parse the input for you. For your example string, it looks like this:
import groovy.util.XmlSlurper // comes with Groovy (using 2.4.4)
def myString = "& quot;".replace(" ","") // your string + replaced whitespaces for correct parsing
def embeddedString = "<tag>" + myString + "</tag>" // tag name can be any name
def tmp = new XmlSlurper().parseText(embeddedString)
println tmp // prints """
The output is what you desired. (and now I may burn)

Resources