code_junkie

How to split a string by using [] in Python

Nov 14th, 2011
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. import re
  2. s = "name[id]"
  3. re.find(r"[(.*?)]", s).group(1) # = 'id'
  4.  
  5. "i,split,on commas".split(',') # = ['i', 'split', 'on commas']
  6.  
  7. import re
  8. s = "name[id]"
  9.  
  10. # split by either a '[' or a ']'
  11. re.split('[|]', s) # = ['name', 'id', '']
  12.  
  13. "name[id]".split('[')[:-1] == "id"
  14.  
  15. "name[id]".split('[')[1].split(']')[0] == "id"
  16.  
  17. re.search(r'[(.*?)]',"name[id]").group(1) == "id"
  18.  
  19. re.split(r'[[]]',"name[id]")[1] == "id"
  20.  
  21. 'name[id]'.split('[', 1)[-1].split(']', 1)[0]
  22.  
  23. 'name[id]'.split('[', 1)[-1].rstrip(']')
  24.  
  25. >>> m = re.match(r'.*[(?P<id>w+)]', 'name[id]')
  26. >>> result_dict = m.groupdict()
  27. >>> result_dict
  28. {'id': 'id'}
  29. >>>
  30.  
  31. >>> s = 'name[id]'
  32.  
  33. >>> s[s.index('[')+1:s.index(']')]
  34. 'id'
  35.  
  36. def between_brackets(text):
  37. return text.partition('[')[2].partition(']')[0]
  38.  
  39. str.split("[")[1].split("]")[0]
Add Comment
Please, Sign In to add comment