hamzah
hamzah

Reputation: 375

How to remove brackets from python string?

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.

Upvotes: 15

Views: 149904

Answers (3)

Michael Amadi
Michael Amadi

Reputation: 134

import re
text = "some (string) [another string] in brackets"
re.sub("\(.*?\)", "", text)
# some in brackets
# works for () and will work for [] if you replace () with [].

The \(.*?\) format matches brackets with some text in them with an unspecified length. And the \[.*?\] format matches also but a square brackets with some text inside the brackets.

The output will not contain brackets and texts inside of them.

If you want to match only square brackets replace square brackets with the bracket of choice and vise versa.

To match () and [] bracket in one go, use this format (\(.*?\)|\[.*?\]:) joining two pattern with the | character.

Upvotes: -1

Nikunj Kakadiya
Nikunj Kakadiya

Reputation: 2998

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)

Upvotes: 3

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

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.

Upvotes: 39

Related Questions