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

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.

Related

Convert string to tuple in python [duplicate]

This question already has answers here:
converting string to tuple
(3 answers)
convert a string which is a list into a proper list python
(3 answers)
Closed 4 years ago.
Pretty simply question but giving me some trouble:
I have
"('A', 'Open')" # type = str
and would like:
('A','Open') # type = tuple
Have tried using .split(), and just converting the whole thing to tuple(str) with no success.
There are two ways to achieve this, both parse the string as Python code.
The seemingly easier option is to use eval.
The slightly more complicated, but better, option is to use ast.literal_eval.
In Using python's eval() vs. ast.literal_eval()? everything has already been said why the latter is almost always what you really want. Note that even the official documentation of eval says that you should use ast.literal_eval instead.
How about this?
import re
m_s = "('A', 'Open')"
patt = r"\w+"
print(tuple(re.findall(patt, m_s)))
How about using regular expressions ?
In [1686]: x
Out[1686]: '(mono)'
In [1687]: tuple(re.findall(r'[\w]+', x))
Out[1687]: ('mono',)
In [1688]: x = '(mono), (tono), (us)'
In [1689]: tuple(re.findall(r'[\w]+', x))
Out[1689]: ('mono', 'tono', 'us')
In [1690]: x = '(mono, tonous)'
In [1691]: tuple(re.findall(r'[\w]+', x))
Out[1691]: ('mono', 'tonous')
Shortest is do
eval("('A','Open')") #will return type as tuple
eval() evaluates and executes string as python expression

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}

'Replace' string function not working in Python [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 7 years ago.
When I do the following:
def encrypt(string):
str(string).replace('0', 'A')
return(string)
encrypt(000)
Only 0 comes out as the output.
What I want to do is replace all 0s with an A to test an encryption program I am going to make. The output I want is AAA.
So why doesn't it work when I try to replace 0 with A?
Python strings are immutable. No method or operator therefore is able to mutate the string in-place as you appear to desire.
Rather, they return a result that you must assign to a name (or return, whatever).
So, use:
return str(string).replace('0', 'A')
BTW, immutable strings are such a great idea that Java and many later languages copied them from Python...:-)
Of course, if you use 000 with NO quotes as the argument, the function has and can have no idea how many zeros you typed -- it just receives the number 0! You'd better pass a string (quotes around it), so probably lose the str here, too.
you need to assign the change to the string.
def encrypt(string):
return str(string).replace('0', 'A')
You will not be able to get 'AAA' out if you pass the NUMBER 000. Because the number 000 is the same as 0 and gets converted to the string '0'. If you properly implement your return/replace function as described in the other answers the result for inputting the number 000 with return 'A'.
Probably you want a new function that you pass strings not numbers otherwise you will never be able to differentiate between 000 and 0 (or any other number of zeros 000000000000, etc)
BTW, you called your function variable "string" even though you are passing a number and then converting it to a string with str. This is good foreshadowing. Here's a function that will do what you want with strings, not numbers:
def encrypt(string):
return string.replace('0', 'A')
>>> encrypt('000')
'AAA'
There is nothing wrong with your code.
You should pass 000 as string if you don't 000 is treated as 0 so you get only one A replacing single 0.
def encrypt(string):
return str(string).replace('0', 'A')
print encrypt('000')
This gives AAA as output.

Python - difference between 'a' and "a"? [duplicate]

This question already has answers here:
Single quotes vs. double quotes in Python [closed]
(19 answers)
Closed 9 years ago.
I have been always mixing these two notations, regarding them both as a string in Python.
What are the differences between them?
Under what circumstances can we only use one of them?
They're the same. The only time it ever matters is that you have to escape the delimiter character: "\"" vs '"'.
Personally, I usually use ' for strings that aren't "user-visible" and " for strings that are, but I'm not completely consistent with that and I don't think it's common practice.
No difference at all: they mean exactly the same thing. Yes, that's unusual for Python ;-)
Some programmers like to put one-character strings in single quotes, and longer strings in double quotes. Probably a habit carried over from C. Do what you like :-)
Ah: a lot more discussion here.
They are equal and depend on your preferences
but you can do this:
>>> print 'Double" quote inside single'
Double" quote inside single
>>> print "Single' quote inside double"
Single' quote inside double
They are the same, though I prefer to use 'single quotes'as they're easier to read

Adding thousand separator while printing a number [duplicate]

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

Categories