How to remove brackets from python string?

99,365

Solution 1

That looks like you have a string inside a list:

["blbal"] 

To get the string just index l = ["blbal"] print(l[0]) -> "blbal".

If it is a string use str.strip '["blbal"]'.strip("[]") or slicing '["blbal"]'[1:-1] if they are always present.

Solution 2

you can also you replace to just replace the text/symbol that you don't want with the empty string.

text = ["blbal","test"]
strippedText = str(text).replace('[','').replace(']','').replace('\'','').replace('\"','')
print(strippedText)
Share:
99,365
hamzah
Author by

hamzah

Updated on December 11, 2021

Comments

  • hamzah
    hamzah over 2 years

    I know from the title you might think that this is a duplicate but it's not.

    for id,row in enumerate(rows):
        columns = row.findall("td")
    
        teamName = columns[0].find("a").text, # Lag
        playedGames = columns[1].text, # S
        wins = columns[2].text,
        draw = columns[3].text,
        lost = columns[4].text,
        dif = columns[6].text, # GM-IM
        points = columns[7].text, # P - last column
    
        dict[divisionName].update({id :{"teamName":teamName, "playedGames":playedGames, "wins":wins, "draw":draw, "lost":lost, "dif":dif, "points":points }})
    

    This is how my Python code looks like. Most of the code is removed but essentially i am extracting some information from a website. And i am saving the information as a dictionary. When i print the dictionary every value has a bracket around them ["blbal"] which causes trouble in my Iphone application. I know that i can convert the variables to strings but i want to know if there is a way to get the information DIRECTLY as a string.

  • frnhr
    frnhr about 9 years
    you probably meant '"[blbal]".strip...'
  • Padraic Cunningham
    Padraic Cunningham about 9 years
    @frnhr, the OP's code seems to have quotes around the inner string, not totally sure what it is exactly but I added single quotes so the OP can use it as an example.
  • hamzah
    hamzah about 9 years
    using string = string[0] worked however that means i would need to add 7 rows like that which i dont like. As my original question where if there was a way to get the it in that format at the first stage meaning from this stage wins = collumns[2].text,
  • Padraic Cunningham
    Padraic Cunningham about 9 years
    If you want all the contents in a single string use " ".join(your_list)
  • hamzah
    hamzah about 9 years
    im sorry i dont know what " " is supposed to be?
  • Padraic Cunningham
    Padraic Cunningham about 9 years
    @hamzah that means each subelement in the list will be separated by an empty string ",".join(your_list) would separate every subelement by a comma etc..