converting string to tuple in python - python

I have a string returnd from a software like "('mono')" from that I needed to convert string to tuple .
that I was thinking using ast.literal_eval("('mono')") but it is saying malformed string.

Since you want tuples, you must expect lists of more than element in some cases. Unfortunately you don't give examples beyond the trivial (mono), so we have to guess. Here's my guess:
"(mono)"
"(two,elements)"
"(even,more,elements)"
If all your data looks like this, turn it into a list by splitting the string (minus the surrounding parens), then call the tuple constructor. Works even in the single-element case:
assert data[0] == "(" and data[-1] == ")"
elements = data[1:-1].split(",")
mytuple = tuple(elements)
Or in one step: elements = tuple(data[1:-1].split(",")).
If your data doesn't look like my examples, edit your question to provide more details.

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')

Convert string to tuple? Just apply tuple:
>>> tuple('(mono)')
('(', 'm', 'o', 'n', 'o', ')')
Now it's a tuple.

Try to this
a = ('mono')
print tuple(a) # <-- you create a tuple from a sequence
#(which is a string)
print tuple([a]) # <-- you create a tuple from a sequence
#(which is a list containing a string)
print tuple(list(a))# <-- you create a tuple from a sequence
# (which you create from a string)
print (a,)# <-- you create a tuple containing the string
print (a)
Output :
('m', 'o', 'n', 'o')
('mono',)
('m', 'o', 'n', 'o')
('mono',)
mono

I assume that the desired output is a tuple with a single string: ('mono',)
A tuple of one has a trailing comma in the form (tup,)
a = '(mono)'
a = a[1:-1] # 'mono': note that the parenthesis are removed removed
# if they are inside the quotes they are treated as part of the string!
b = tuple([a])
b
> ('mono',)
# the final line converts the string to a list of length one, and then the list to a tuple

Related

Split and join element in 2D array

I am newbie in python. I have split a list which contains 100 separate string. It all have 300 chars in it. After splitting, it became to act like 2D array and I want to join them together to get an list in the beginning.
Below is my sample list and what I have tried but it does not work. I want to replace ' ' instead of '1' and remove less than 3 length of chars and join them together. Only replacing function does not work, I cannot remove words this situation.
1 c1|FaAO120O'8ovfoy1W#atvGs1[1s1[1/1]O-a8o1-...
2 O8v^10O#to1'#^'^tv1^]s111t01Otaq>-ata_1...
3 *#^-G1_#O-#b^'ta8a2%e1|28Oot^12#O-#ys1>c...
def tokenize(text):
return text.split("1")
def trimm(text):
return ' '.join([i for i in data if len(i) > 3])
token_data = [tokenize(i) for i in X]
#trim_data = [trimm(i) for i in token_data]
for n in token_data:
for i in token_data[n]:
res=trimm(i)
Below is after tokenize function.
['c', '|FaAO', "20O'8o\x02vfoy", 'W#at\x1bvGs', '[', 's', '[', '/', ']O-a8o', '-\x1b-\x03\x1b#', '^]', '-a\x02\x1b', 'av', 'vc]]\x1b#a\x02d', ']#^-', 'O', 'v\x1bz\x1b#\x1b', "A\x1b'#\x1bvva^\x02", '\x03#^cd0t', '^\x02s', '[', '\x03o', "-\x1b\x02^'Ocv\x1b", 'Ov', 'W\x1b88', 'Ov', 'O', '-\x1b\x02tO8', '\x03#\x1bOf', 'A^W\x02\x08', '', '>0\x1b', 'av', '\x03\x1ba\x02d', 't#\x1bOt\x1bA', 'Wat0s', '[', 'gO8oA^8', 'Wat0', 'v^-\x1b', 'vc__\x1bvv', '\x03ct', 't0\x1b', 't#\x1bOt-\x1b\x02tv', '\x03\x1ba\x02d', "'#^zaA\x1bA", 't0#^cd0', '0\x1b#s', '[', "'vo_0aOt#avt", 'O#\x1b', '\x02^t', 'vOtav]O_t^#o\x08', '', '>^-']
Below is after trimm function
|FaAO 20O'8ovfoy W#atvGs ]O-a8o --# -a vc]]#ad ]#^- vz# A'#vva^ #^cd0t -^'Ocv W88 -tO8 #Of A^W ad t#OtA Wat0s gO8oA^8 Wat0 v^- vc__vv t#Ot-tv ad '#^zaAA t0#^cd0 0#s 'vo_0aOt#avt vOtav]O_t^#
I can do above situation only one 300 chars string. However I want it to do all strings in the original list. Therefore how can I make a loop that trimm and join every string ?
These two lines look wrong:
for n in token_data:
for i in token_data[n]:
n will be an element of token_data, taking token_data[n] does not make sense to me, since n is not an index, instead I would use for i in n: for the second for loop.

Issue with Configobj-python and list items

I am trying to read .ini file with keywords having single items or list items. When I try to print single item strings and float values, it prints as h,e,l,l,o and 2, ., 1 respectively, whereas it should have been just hello and 2.1. Also, when I try to write new single item string/float/integer, there is , at the end. I am new to python and dealing with configobj. Any help is appreciated and if this question has been answered previously, please direct me to it. Thanks!
from configobj import ConfigObj
Read
config = ConfigObj('para_file.ini')
para = config['Parameters']
print(", ".join(para['name']))
print(", ".join(para['type']))
print(", ".join(para['value']))
Write
new_names = 'hello1'
para['name'] = [x.strip(' ') for x in new_names.split(",")]
new_types = '3.1'
para['type'] = [x.strip(' ') for x in new_types.split(",")]
new_values = '4'
para['value'] = [x.strip(' ') for x in new_values.split(",")]
config.write()
My para_file.ini looks like this,
[Parameters]
name = hello1
type = 2.1
value = 2
There are two parts to your question.
Options in ConfigObj can be either a string, or a list of strings.
[Parameters]
name = hello1 # This will be a string
pets = Fluffy, Spot # This will be a list with 2 items
town = Bismark, ND # This will also be a list of 2 items!!
alt_town = "Bismark, ND" # This will be a string
opt1 = foo, # This will be a list of 1 item (note the trailing comma)
So, if you want something to appear as a list in ConfigObj, you must make sure it includes a comma. A list of one item must have a trailing comma.
In Python, strings are iterable. So, even though they are not a list, they can be iterated over. That means in an expression like
print(", ".join(para['name']))
The string para['name'] will be iterated over, producing the list ['h', 'e', 'l', 'l', 'o', '1'], which Python dutifully joins together with spaces, producing
h e l l o 1

Find all substrings in a string using recursion Python 3

How would you make a list of all the possible substrings in a string using recursion? (no loops) I know that you can recurse using s[1:] to cut off the first position and s[:-1] to cut off the last position. So far I have come up with this:
def lst_substrings(s):
lst = []
if s == "":
return lst
else:
lst.append(s)
return lst_substrings(s[1:])
but this would only make a list of all the substrings that are sliced by the first position if it worked
Fun problem, here's my solution - feedback appreciated.
Output
In [73]: lstSubStrings("Hey")
Out[73]: ['', 'y', 'H', 'Hey', 'He', 'e', 'ey']
Solution
def lstSubStrings(s):
# BASE CASE: when s is empty return the empty string
if(len(s) is 0):
return [s]
substrs = []
# a string is a substring of itself - by the definition of subset in math
substrs.append(s)
# extend the list of substrings by all substrings with the first
# character cut out
substrs.extend(lstSubStrings(s[1:]))
# extend the list of substrings by all substrings with the last
# character cut out
substrs.extend(lstSubStrings(s[:-1]))
# convert the list to `set`, removing all duplicates, and convert
# back to a list
substrs = list(set(substrs))
return substrs
EDIT: Duh. Just realized now that practically the same solution has been posted by someone who was quicker than me. Vote for his answer. I'll leave this as it is a bit more concise and in case you want to sort the resulting list by substring length. Use len(item, item), i.e. leave the - sign, to sort in ascending order.
This will do:
def lst_substrings(s):
lst = [s]
if len(s) > 0:
lst.extend(lst_substrings(s[1:]))
lst.extend(lst_substrings(s[:-1]))
return list(set(lst))
sub = lst_substrings("boby")
sub.sort(key=lambda item: (-len(item), item))
print(sub)
Output is:
['boby', 'bob', 'oby', 'bo', 'by', 'ob', 'b', 'o', 'y', '']

Python Concatenate string with all members of a list and display each display result separated by commas

I'm trying to do something like a "conjugator".
Say I have a list of endings:
endings = ['o', 'es', 'e', 'emos', 'eis', 'em']
and I have a verb root as a string:
root = "com"
The way I thought of doing this is:
for ending in endings:
print root + ending
which outputs:
como
comes
come
comemos
comeis
comem
But my desired result is:
como, comes, come, comemos, comeis, comem
How can I achieve exactly this (and with no quotes around each of the resulting items, and no comma after the last item)?
You need a list comprehension and str.join(). From the documentation:
str.join(iterable)
Return a string which is the concatenation of the
strings in the iterable iterable. The separator between elements is
the string providing this method.
>>> root = "com"
>>> endings = ['o', 'es', 'e', 'emos', 'eis', 'em']
>>> verbs = [root + ending for ending in endings]
>>> print ", ".join(verbs)
como, comes, come, comemos, comeis, comem

Replace one string in a list of strings

I have a list of strings.
If one of the strings (e.g. at index 5) is the empty string, I want to replace it with "N".
How do I do that? The naive method (for a java programmer) does not work:
string_list[5] = "N"
gives
'str' object does not support item assignment
(string_list originally came from a .csv-file- that is why it might contain empty strings.)
Your error seems to indicate that your string_list is not a list of string but a real string (that doesn't support assignement because a string is immutable).
If your string_list was a real list of strings, like this for example : string_list = ["first", "second", "", "fourth"], then you will be able to do string_list[2] = "third" to obtain string_list = ["first", "second", "third", "fourth"].
If you need to automatically detect where an empty string is located in your list, try with index :
string_list[string_list.index("")] = "replacement string"
print string_list
>>> ["first", "second", "replacement string", "fourth"]
You say you have a list of strings but from you error it looks like you're trying to index a string
l = ["a", "b", "", "c"]
Is a list of strings.
l = ["N" if not x else x for x in l]
Is a list of strings with empty strings replaced with "N"
Try this:
>>> s = 'abc de'
>>> s.replace(' ', 'N')
'abcNde'
As mentioned by the others, it sounds like string_list is actually a string itself, meaning that you can't use assignment to change a character.
In python work with lists and convert them to strings when need be.
>> str = list("Hellp")
>> str
['H', 'e', 'l', 'l', 'p']
>> str[4] = 'o'
>> str
['H', 'e', 'l', 'l', 'o']
TO make it a string use
>> "".join(str)
'Hello World'
Python strings are immutable and they cannot be modified.
Or you could use List Comprehensions.
Some thing like:
>> myStr = ['how', 'are', 'yew', '?']
>> myStr = [w.replace('yew', 'you') for w in myStr]
The following example iterates through lists of lists (sublists), in order to replace a string, a word:
myoldlist=[['aa bbbbb'],['dd myword'],['aa myword']]
mynewlist=[]
for i in xrange(0,3,1):
mynewlist.append([x.replace('myword', 'new_word') for x in myoldlist[i]])
print mynewlist
# ['aa bbbbb'],['dd new_word'],['aa new_word']

Categories

Resources