How to place dots into the number with Python? - python

How can I automatically place dots by separating it with 3 digits in a group beginning from the right?
Example:
in: 1234; out 1.234
in: 12345678; out 12.345.678

You are looking for a thousands-separator. Format your number with the format() function to using commas as the thousands separator, then replace the commas with dots:
>>> format(1234, ',').replace(',', '.')
'1.234'
>>> format(12345678, ',').replace(',', '.')
'12.345.678'
Here the ',' format signals that the decimal number should be formatted with a thousands-separator (see the Format Specification Mini-language).
The same can be achieved in a wider string format with the str.format() method, where placeholders in the template are replaced with values:
>>> 'Some label for the value: {:,}'.format(1234).replace(',', '.')
'Some label for the value: 1,234'
but then you run the risk of accidentally replacing other full stops in the output string too!
Your other option would be to use the locale-dependent 'n' format, but that requires your machine to be configured for a locale that sets the right LC_NUMERIC options.

Here is a simple solution:
>>> a = 12345678
>>> "{:,}".format(a)
'12,345,678'
>>> "{:,}".format(a).replace(",", ".")
'12.345.678'
>>>
This uses the .format method of a string to add the comma separators and then the .replace method to change those commas to periods.

Related

Python format leading zeros and thousands comma

I know that I can use the following to pad leading zeros to a string:
>>> qty = 1
>>> '{:06}'.format(qty)
'000001'
But can I also use the format function to also add thousands separators to get:
'000,001'
I know this can be done by manipulating the text, but can it be achieved with the format() function ?

How to remove set of characters when a string comprise of "\" and Special characters in python

a = "\Virtual Disks\DG2_ASM04\ACTIVE"
From the above string I would like to get the part "DG2_ASM04" alone. I cannot split or strip as it has the special characters "\", "\D" and "\A" in it.
Have tried the below and can't get the desired output.
a.lstrip("\Virtual Disks\\").rstrip("\ACTIVE")
the output I have got is: 'G2_ASM04' instead of "DG2_ASM04"
Simply use slicing and escape backslash(\)
>>> a.split("\\")[-2]
'DG2_ASM04'
In your case D is also removing because it is occurring more than one time in given string (thus striping D as well). If you tweak your string then you will realize what is happening
>>> a = "\Virtual Disks\XG2_ASM04\ACTIVE"
>>> a.lstrip('\\Virtual Disks\\').rstrip("\\ACTIVE")
'XG2_ASM04'

Strip all characters after the final dash in a string in Python, and test if numeric?

If I have a string:
string = 'this-is-a-string-125'
How can I grab the last set of characters after the dash and check if they are digits?
If you want to verify that they are actually digits, you can do
x.rsplit('-', 1)[1].isdigit()
"Numeric" is a more general criteria that could be interpreted different ways. For instance "12.87" is numeric in some sense, but not all the characters are digits.
You can do int(x.rsplit('-', 1)[1]) to see if the string can be interpreted as a integer, or float(x.rsplit('-', 1)[1]) to see if it can be interpreted as a float. (These will raise a ValueError if the string isn't numeric in the appropriate sense, so you can catch that exception and do whatever you need to do if it's not numeric.)
s = 'this-is-a-string-125'.split('-')[-1].isdigit()
We split the string by dash ('-') which gives a list of substrings (see split()). We then take the last one ([-1]) and we verify that that string contains only digits (isdigit()):
>>> 'this-is-a-string-125'.split('-')
['this', 'is', 'a', 'string', '125']
>>> 'this-is-a-string-125'.split('-')[-1]
'125'
>>> 'this-is-a-string-125'.split('-')[-1].isdigit()
True
Nobody knows about partition or rpartition:
text.rpartition("-")[-1].isdigit()
How about:
str.split('-')[-1].isdigit()
Seems like a simple regex can do both the stripping and checking:
>>> import re
>>> s = 'this-is-a-string-125'
>>> m = re.search(r'-(\d+)$', s)
>>> m.group(1)
'125'
>>> s[:m.start()] # gives you what was stripped away.
'this-is-a-string'
Match object m will be None if the string lacks a dash character followed by one or more digits at the end.

How to convert an integer to hexadecimal without the extra '0x' leading and 'L' trailing characters in Python?

I am trying to convert big integer number to hexadecimal, but in result I get extra "0x" in the beginning and "L" at the and. Is there any way to remove them. Thanks.
The number is:
44199528911754184119951207843369973680110397865530452125410391627149413347233422
34022212251821456884124472887618492329254364432818044014624401131830518339656484
40715571509533543461663355144401169142245599341189968078513301836094272490476436
03241723155291875985122856369808620004482511813588136695132933174030714932470268
09981252011612514384959816764532268676171324293234703159707742021429539550603471
00313840833815860718888322205486842202237569406420900108504810
In hex I get:
0x2ef1c78d2b66b31edec83f695809d2f86e5d135fb08f91b865675684e27e16c2faba5fcea548f3
b1f3a4139942584d90f8b2a64f48e698c1321eee4b431d81ae049e11a5aa85ff85adc2c891db9126
1f7f2c1a4d12403688002266798ddd053c2e2670ef2e3a506e41acd8cd346a79c091183febdda3ca
a852ce9ee2e126ca8ac66d3b196567ebd58d615955ed7c17fec5cca53ce1b1d84a323dc03e4fea63
461089e91b29e3834a60020437db8a76ea85ec75b4c07b3829597cfed185a70eeaL
The 0x is literal representation of hex numbers. And L at the end means it is a Long integer.
If you just want a hex representation of the number as a string without 0x and L, you can use string formatting with %x.
>>> a = 44199528911754184119951207843369973680110397
>>> hex(a)
'0x1fb62bdc9e54b041e61857943271b44aafb3dL'
>>> b = '%x' % a
>>> b
'1fb62bdc9e54b041e61857943271b44aafb3d'
Sure, go ahead and remove them.
hex(bignum).rstrip("L").lstrip("0x") or "0"
(Went the strip() route so it'll still work if those extra characters happen to not be there.)
Similar to Praveen's answer, you can also directly use built-in format().
>>> a = 44199528911754184119951207843369973680110397
>>> format(a, 'x')
'1fb62bdc9e54b041e61857943271b44aafb3d'
I think it's dangerous idea to use strip.
because lstrip or rstrip strips 0.
ex)
a = '0x0'
a.lstrip('0x')
''
result is '', not '0'.
In your case, you can simply use replace to prevent above situation.
Here's sample code.
hex(bignum).replace("L","").replace("0x","")
Be careful when using the accepted answer as lstrip('0x') will also remove any leading zeros, which may not be what you want, see below:
>>> account = '0x000067'
>>> account.lstrip('0x')
'67'
>>>
If you are sure that the '0x' prefix will always be there, it can be removed simply as follows:
>>> hex(42)
'0x2a'
>>> hex(42)[2:]
'2a'
>>>
[2:] will get every character in the string except for the first two.
A more elegant way would be
hex(_number)[2:-1]
but you have to be careful if you're working with gmpy mpz types,
then the 'L' doesn't exist at the end and you can just use
hex(mpz(_number))[2:]

Output first 100 characters in a string

Can seem to find a substring function in python.
Say I want to output the first 100 characters in a string, how can I do this?
I want to do it safely also, meaning if the string is 50 characters it shouldn't fail.
print my_string[0:100]
From python tutorial:
Degenerate slice indices are handled
gracefully: an index that is too large
is replaced by the string size, an
upper bound smaller than the lower
bound returns an empty string.
So it is safe to use x[:100].
Easy:
print mystring[:100]
To answer Philipp's concern ( in the comments ), slicing works ok for unicode strings too
>>> greek=u"αβγδεζηθικλμνξοπρςστυφχψω"
>>> print len(greek)
25
>>> print greek[:10]
αβγδεζηθικ
If you want to run the above code as a script, put this line at the top
# -*- coding: utf-8 -*-
If your editor doesn't save in utf-8, substitute the correct encoding
Slicing of arrays is done with [first:last+1].
One trick I tend to use a lot of is to indicate extra information with ellipses. So, if your field is one hundred characters, I would use:
if len(s) <= 100:
print s
else:
print "%s..."%(s[:97])
And yes, I know () is superfluous in this case for the % formatting operator, it's just my style.
String formatting using % is a great way to handle this. Here are some examples.
The formatting code '%s' converts '12345' to a string, but it's already a string.
>>> '%s' % '12345'
'12345'
'%.3s' specifies to use only the first three characters.
>>> '%.3s' % '12345'
'123'
'%.7s' says to use the first seven characters, but there are only five. No problem.
>>> '%.7s' % '12345'
'12345'
'%7s' uses up to seven characters, filling missing characters with spaces on the left.
>>> '%7s' % '12345'
' 12345'
'%-7s' is the same thing, except filling missing characters on the right.
>>> '%-7s' % '12345'
'12345 '
'%5.3' says use the first three characters, but fill it with spaces on the left to total five characters.
>>> '%5.3s' % '12345'
' 123'
Same thing except filling on the right.
>>> '%-5.3s' % '12345'
'123 '
Can handle multiple arguments too!
>>> 'do u no %-4.3sda%3.2s wae' % ('12345', 6789)
'do u no 123 da 67 wae'
If you require even more flexibility, str.format() is available too. Here is documentation for both.
Most of previous examples will raise an exception in case your string is not long enough.
Another approach is to use
'yourstring'.ljust(100)[:100].strip().
This will give you first 100 chars.
You might get a shorter string in case your string last chars are spaces.
[start:stop:step]
So If you want to take only 100 first character, use your_string[0:100] or your_string[:100]
If you want to take only the character at even position, use your_string[::2]
The "default values" for start is 0, for stop - len of string, and for step - 1. So when you don't provide one of its and put ':', it'll use it default value.

Categories

Resources