-2

would really appreciate any help on this one!

I have a string:

"<Cell 'test'.B45>"

I need to convert this to a tuple with only one object in it, so that looks like this:

((<Cell 'test'.B45>))

So to do this I have tried:

string = "<Cell 'test'.B45>"
tuple = eval(string)

this returns:

SyntaxError: invalid syntax

I think that this is because of the special values ("<",">", "'") in the string (removing them seems to work but I need them here)

Am I right here? and is there a way round this? note I have also tried using the method:

tuple = ast.literal_eval(string)

with the same result.

quamrana
  • 37,849
  • 12
  • 53
  • 71
11l
  • 73
  • 1
  • 9
  • 6
    The string `eval` recieves must be valid Python code, which yours is not. To create a tuple with just one element write `my_tuple = (my_element, )`. – Jorge Luis Mar 25 '23 at 18:06
  • Does this answer your question? [How to create a "singleton" tuple with only one element](https://stackoverflow.com/questions/12876177/how-to-create-a-singleton-tuple-with-only-one-element) – Jorge Luis Mar 25 '23 at 18:07
  • 1
    You could also alternatively do that without parentheses: `my_tuple = my_element,` – slothrop Mar 25 '23 at 18:11
  • It isn't really clear what your question is. Why do you have this string and what object are you trying to turn it into? – ndc85430 Mar 25 '23 at 18:29

1 Answers1

0

Is that what you're saying?


string = "<Cell 'test'.B45>"
list_of_str = list()
list_of_str.append(string)
tuple_info = tuple(list_of_str)
print(tuple_info)


# ("<Cell 'test'.B45>",)
chrisfang
  • 309
  • 5
  • 2
    Why not just use a tuple literal? `(string,)`? – Brian61354270 Mar 25 '23 at 18:27
  • @Brian61354270 I'm trying to figure out his specific needs and scenarios, These methods, which have been reviewed above, And I'm just adding other ways, For the complementary approach, I'm trying to understand what does he mean by conversion Because the above method is directly literal assignment. – chrisfang Mar 25 '23 at 18:36
  • Thank you Chris, this got me there! ( just had to add the below to the end: cell = (tuple(list_of_str),) making it a tuple of tuples. For those interested, I am returning named ranges from excel (using openpyxl) when a range with lots of cells next to each other is selected it returns a tuple of tuples with the worksheet and cell in it. When only 1 cell is in the excel named range it returns just a cell, so I wanted to convert this cell into the same format as the other returns. Thank you all for your help! – 11l Mar 25 '23 at 20:39