how to split a string at special symbol in python?

Viewed 72

I have this string:

  x = "G5.jpg']"

and I wish to split it at the symbol ' so that then I have G5.jpg and ] seperately in a list. Anyone has an idea how to do this? I have tried this:

    name = x.split["'"]

but it doesnt split the string. I appreciate any help :)

3 Answers

You can do this:

x = "G5.jpg']"
name = x.split("'") # name = ["G5.jpg", "]"
# To get only the "G5.jpg" use this:
name = x.split("'") [0]

In your code you have x.split["'"] - This is incorrect syntax.

Calling x.split("'") will return a list. You just then simply take the first element from that returned list

x = "G5.jpg']"
parts = x.split("'")
# parts now == ['G5.jpg', ']']
name = parts[0]
# name now == 'G5.jpg'

Use regular expressions and re.findall to return all captured matches:

import re
x = "G5.jpg']"
name = re.findall(r"[^']+", x)
print(name)
# ['G5.jpg', ']']
Related