Adding thousand separator while printing a number [duplicate] - python

This question already has answers here:
How to print a number using commas as thousands separators
(30 answers)
Closed 9 years ago.
I don't really know the "name" for this problem, so it might be a incorrect title, but the problem is simple, if I have a number
for example:
number = 23543
second = 68471243
I want to it make print() like this.
23,543
68,471,243
I hope this explains enough or else add comments.
Any help is appreciated!

If you only need to add comma as thousand separator and are using Python version 3.6 or greater:
print(f"{number:,g}")
This uses the formatted string literals style. The item in braces {0} is the object to be formatted as a string. The colon : states that output should be modified. The comma , states that a comma should be used as thousands separator and g is for general number. [1]
With older Python 3 versions, without the f-strings:
print("{0:,g}".format(number))
This uses the format-method of the str-objects [2]. The item in braces {0} is a place holder in string, the colon : says that stuff should be modified. The comma , states that a comma should be used as thousands separator and g is for general number [3]. The format-method of the string object is then called and the variable number is passed as an argument.
The 68,471,24,3 seems a bit odd to me. Is it just a typo?
Formatted string literals
Python 3 str.format()
Python 3 Format String Syntax

The easiest way is setting the locale to en_US.
Example:
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
number = 23543
second = 68471243
print locale.format("%d", number, grouping=True)
print locale.format("%d", second, grouping=True)
prints:
23,543
68,471,243

Related

How to input a variable string into re.search in python [duplicate]

This question already has answers here:
How to use a variable inside a regular expression?
(12 answers)
Closed 4 years ago.
Initially I had my date regex working as follows, to capture "February 12, 2018" for example
match = re.search(r'(January|February|March|April|May|June|July|August|September?|October?|November|December)\s+\d{1,2},\s+\d{4}', date).group()
But I want it to become more flexible, and input my variable string into my regex but I can't seem to get it to work after looking through many of the stackoverflow threads about similar issues. I'm quite a novice so I'm not sure what's going wrong. I'm aware that simply MONTHS won't work. Thank you
MONTHS = "January|February|March|April|May|June|July|August|September|October|November|December"
match = re.search(r'(MONTHS)\s+\d{1,2},\s+\d{4}', date).group()
print(match)
'NoneType' object has no attribute 'group'
You've got MONTHS as just a part of the match string, python doesn't know that it's supposed to be referencing a variable that's storing another string.
So instead, try:
match = re.search(r'(' + MONTHS + ')\s+\d{1,2},\s+\d{4}', date).group()
That will concatenate (stick together) three strings, the first bit, then the string stored in your MONTHS variable, and then the last bit.
If you want to substitute something into a string, you need to use either format strings (whether an f-string literal or the format or format_map methods on string objects) or printf-style formatting (or template strings, or a third-party library… but usually one of the first two).
Normally, format strings are the easiest solution, but they don't play nice with strings that need braces for other purposes. You don't want that {4} to be treated as "fill in the 4th argument", and escaping it as {{4}} makes things less readable (and when you're dealing with regular expressions, they're already unreadable enough…).
So, printf-style formatting is probably a better option here:
pattern = r'(%s)\s+\d{1,2},\s+\d{4}' % (MONTHS,)
… or:
pattern = r'(%(MONTHS)s)\s+\d{1,2},\s+\d{4}' % {'MONTHS': MONTHS}

Output of print("""Hello World's"s""""") in python 3.6 [duplicate]

This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 4 years ago.
I read that anything between triple quotes inside print is treated literal so tried messing things a little bit. Now I am not able to get above statement working. I searched internet but could not find anything.
statement:
print("""Hello World's"s""""")
Output I am getting:
Hello World's"s
Expected output:
Hello World's"s""
print("""Hello World's"s""""") is seen as print("""Hello World's"s""" "") because when python find """ it automatically ends the previous string beginning with a triple double-quote.
Try this:
>>> print("a"'b')
ab
So basically your '"""Hello World's"s"""""' is just <str1>Hello World's"s</str1><str2></str2> with str2 an empty string.
Triple quoted string is usually used for doc-string.
As #zimdero pointed out Triple-double quote v.s. Double quote
You can also read https://stackoverflow.com/a/19479874/1768843
And https://www.python.org/dev/peps/pep-0257/
If you really want to get the result you want just use \" or just you can do combination with ``, .format() etc
print("Hello World's\"s\"\"")
https://repl.it/repls/ThatQuarrelsomeSupercollider
Triple quotes within a triple-quoted string must still be escaped for the same reason a single quote within a single quoted string must be escaped: The string parsing ends as soon as python sees it. As mentioned, once tokenized your string is equivalent to
"""Hello World's"s""" ""
That is, two strings which are then concatenated by the compiler. Triple quoted strings can include newlines. Your example is similar to
duke = """Thou seest we are not all alone unhappy:
This wide and universal theatre
Presents more woeful pageants than the scene
Wherein we play in."""
jaques = """All the world's a stage,
And all the men and women merely players:
They have their exits and their entrances;
And one man in his time plays many parts."""
If python was looking for the outermost triple quotes it would only have defined one string here.
Simple with ''' to not complicate things:
print('''Hello World's"s""''')
Maybe this is what you are looking for?
print("\"\"Hello World's's\"\"")
Output:
""Hello World's's""

String capitalize with python

Now I Am doing very small question at HackRank about string manipulations it is very easy one just like homework dump . The question is turn a given string to capitalize they mentioned their question just like below
You are given a string . Your task is to capitalize each word of S.
Input Format
A single line of input containing the string, S.
Constraints
0< len(s) <1000
The string consists of alphanumeric characters and spaces.
Output Format
Sample Input
hello world
Sample Output
Hello World
I have done here I wrote a two line script from python and I submitted it but
they said it is a wrong answer but I can't understand why is that my code is follow
l=list(map(str.capitalize,input().strip(' ').split()))
print(' '.join(l))
Can anyone tell me what is wrong with my code
(it fails on test cases 1 / 3 / 4 / 5 with Python 3, so )
?
Use str.title
>>>'aba aba'.title()
'Aba Aba'
If you don't specifiy the separator to str.split(), "any whitespace string is a separator and empty strings are removed from the result." Note that here "whitespace" includes tabs, newlines etc.
The problem is not clearly specified (there's no definition of what "word" means) and we don't know what they use for test cases, but I assume they have a couple string with newlines or such. Anyway: explicitely specifying " " as the separator makes the tests pass:
# Python 2
s = raw_input()
print " ".join(x.capitalize() for x in s.strip().split(" "))
# Python 3
s = input()
print(" ".join(x.capitalize() for x in s.strip().split(" ")))
I presume the error is on input(). If HackRank is using python 2.7, this will try to evaluate the input, rather than returning a string. Thus, an input hello world will try to evaluate this string, which is nonsense. If you try raw_input() in stead, this should fix this problem.

How to avoid converting an integer to string when concatenating [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 9 years ago.
I know that in python, you can't simply do this:
number = 1
print "hello number " + number
you have to do this:
print "hello number " + str(number)
otherwise you'll get an error.
My question is then, being python such a compact language and this feature of automatic casting/converting from integer to string available in so many other languages, isn't there away to avoid having to use the str() function everytime? Some obscure import, or simply another way to do it?
Edit: When I say another way, I mean simpler more compact way to write it. So, I wouldn't really consider format and alternative for instance.
Thanks.
You can avoid str():
print 'hello number {}'.format(number)
Anyway,
'abc' + 123
is equivalent to
'abc'.__add__(123)
and the __add__ method of strings accepts only strings.
Just like
123 + 'abc'
is equivalent to
(123).__add__('abc')
and the __add__ method of integers accept only numbers (int/float).
You can use string formatting, old:
print "hello number %s" % number
or new:
print "hello number {}".format(number)
I tend to use the more compact format
>>> print "one",1,"two",2
one 1 two 2
Or, in python 3,
>>> print("one",1,"two",2)
one 1 two 2
Notice however that both options will always introduce a space between each argument, which makes it unsuitable for more complex output formatting, where you should use some of the other solutions presented.
As this answer explains, this will not happen in Python because it is strongly typed. This means that Python will not convert types that you do not explicitly say to convert.

How can I print a string using .format(), and print literal curly brackets around my replaced string [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I print a literal “{}” characters in python string and also use .format on it?
Basically, I want to use .format(), like this:
my_string = '{{0}:{1}}'.format('hello', 'bonjour')
And have it match:
my_string = '{hello:bonjour}' #this is a string with literal curly brackets
However, the first piece of code gives me an error.
The curly brackets are important, because I'm using Python to communicate with a piece of software via text-based commands. I have no control over what kind of formatting the fosoftware expects, so it's crucial that I sort out all the formatting on my end. It uses curly brackets around strings to ensure that spaces in the strings are interpreted as single strings, rather than multiple arguments — much like you normally do with quotation marks in file paths, for example.
I'm currently using the older method:
my_string = '{%s:%s}' % ('hello', 'bonjour')
Which certainly works, but .format() seems easier to read, and when I'm sending commands with five or more variables all in one string, then readability becomes a significant issue.
Thanks!
Here is the new style:
>>> '{{{0}:{1}}}'.format('hello', 'bonjour')
'{hello:bonjour}'
But I thinking escaping is somewhat hard to read, so I prefer to switch back to the older style to avoid escaping:
>>> '{%s:%s}' % ('hello', 'bonjour')
'{hello:bonjour}'

Categories