Convert string to tuple in python [duplicate] - python

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

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}

Ignore special characters when creating a regular expression in python [duplicate]

This question already has answers here:
Escaping regex string
(4 answers)
Closed 6 years ago.
Is there a way to ignore special character meaning when creating a regular expression in python? In other words, take the string "as is".
I am writing code that uses internally the expect method from a Telnet object, which only accepts regular expressions. Therefore, the answer cannot be the obvious "use == instead of regular expression".
I tried this
import re
SPECIAL_CHARACTERS = "\\.^$*+?{}[]|():" # backslash must be placed first
def str_to_re(s):
result = s
for c in SPECIAL_CHARACTERS:
result = result.replace(c,'\\'+c)
return re.compile(result)
TEST = "Bob (laughing). Do you know 1/2 equals 2/4 [reference]?"
re_bad = re.compile(TEST)
re_good = str_to_re(TEST)
print re_bad.match(TEST)
print re_good.match(TEST)
It works, since the first one does not recognize the string, and the second one does. I looked at the options in the python documentation, and was not able to find a simpler way. Or are there any cases my solution does not cover (I used python docs to build SPECIAL_CHARACTERS)?
P.S. The problem can apply to other libraries. It does not apply to the pexpect library, because it provides the expect_exact method which solves this problem. However, someone could want to specify a mix of strings (as is) and regular expressions.
If 'reg' is the regex, you gotta use a raw string as follows
pat = re.compile(r'reg')
If reg is a name bound to a regex str, use
reg = re.escape(reg)
pat = re.compile(reg)

Python generate string based on regex format [duplicate]

This question already has answers here:
Reversing a regular expression in Python
(8 answers)
Closed 1 year ago.
I have some difficulties learning regex in python. I want to parse my tornado web route configuration along with arguments into a request path string without handlers request.path method.
For example, I have route with patterns like:
/entities/([0-9]+)
/product/([0-9]+/actions
The expected result combine with integer parameter (123) will be a string like:
/entities/123
/product/123/actions
How do I generate string based on that pattern?
Thank you very much in advance!
This might be a possible duplicate to:
Reversing a regular expression in Python
Generate a String that matches a RegEx in Python
Using the answer provided by #bjmc a solution works like this:
>>> import rstr
>>> intermediate = rstr.xeger(\d+)
>>> path = '/product/' + intermediate + '/actions'
Depending on how long you want your intermediate integer, you could replace the regex: \d{1,3}

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 to convert a list of longs into a comma separated string in python [duplicate]

This question already has answers here:
How would you make a comma-separated string from a list of strings?
(15 answers)
Closed 6 years ago.
I'm new to python, and have a list of longs which I want to join together into a comma separated string.
In PHP I'd do something like this:
$output = implode(",", $array)
In Python, I'm not sure how to do this. I've tried using join, but this doesn't work since the elements are the wrong type (i.e., not strings). Do I need to create a copy of the list and convert each element in the copy from a long into a string? Or is there a simpler way to do it?
You have to convert the ints to strings and then you can join them:
','.join([str(i) for i in list_of_ints])
You can use map to transform a list, then join them up.
",".join( map( str, list_of_things ) )
BTW, this works for any objects (not just longs).
You can omit the square brackets from heikogerlach's answer since Python 2.5, I think:
','.join(str(i) for i in list_of_ints)
This is extremely similar, but instead of building a (potentially large) temporary list of all the strings, it will generate them one at a time, as needed by the join function.
and yet another version more (pretty cool, eh?)
str(list_of_numbers)[1:-1]
Just for the sake of it, you can also use string formatting:
",".join("{0}".format(i) for i in list_of_things)

Categories