Python Forum
Removing internal brackets from a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Removing internal brackets from a string
#4
iterate over elements in the tuple and recursively flatten it

spam = (((2517.0, 2525.0), 2437.0), 2440.0)


def flatten(arg):
    flat_list = []
    for item in arg:
        if isinstance(item, (tuple, list)):
            flat_list.extend(flatten(item))
        else:
            flat_list.append(item)
    return tuple(flat_list)
print(flatten(spam))

alternative is - to convert to str, remove all brackets and use ast.literal_eval to convert back to tuple

from ast import literal_eval
spam = (((2517.0, 2525.0), 2437.0), 2440.0)
spam = str(spam).replace('(', '').replace(')', '')
spam = literal_eval(spam)
print(spam)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: Removing internal brackets from a string - by buran - Jun-04-2020, 07:09 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [SOLVED] [BeautifulSoup] Why does it turn inserted string's brackets into </>? Winfried 0 1,578 Sep-03-2022, 11:21 PM
Last Post: Winfried
  Removing Space between variable and string in Python coder_sw99 6 6,433 Aug-23-2022, 01:15 PM
Last Post: louries
  Reading list items without brackets and quotes jesse68 6 4,762 Jan-14-2022, 07:07 PM
Last Post: jesse68
  Data pulled from SQL comes in brackets nickzsche 3 2,784 Jan-04-2022, 03:39 PM
Last Post: ibreeden
  For Loop and Use of Brackets to Modify Dictionary in Tic-Tac-Toe Game new_coder_231013 7 2,354 Dec-28-2021, 11:32 AM
Last Post: new_coder_231013
  web socket server handle onnection closed abnormally [internal]) korenron 0 2,180 Sep-23-2021, 09:26 AM
Last Post: korenron
  500 internal server error Nitil 1 2,936 May-01-2021, 06:16 PM
Last Post: snippsat
  Getting a certain value from inside brackets. LeoT 5 3,098 Mar-01-2021, 03:34 PM
Last Post: buran
  Taking brackets out of list in print statement pythonprogrammer 3 2,463 Apr-13-2020, 12:25 PM
Last Post: perfringo
  printing a list contents without brackets in a print statement paracelx 1 2,170 Feb-15-2020, 02:15 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020