0

How do I split this:

str = "['A20150710', 1.0]" to get 'A20150710'?

I tried the below line but not sure how to proceed from there:

str.split(',')
user308827
  • 21,018
  • 70
  • 229
  • 377
  • Let's take a step back, how did you get this: `str = "['A20150710', 1.0]"`? That looks like a string representation of a list. Indeed, your title implies that, but note, **there are no lists here** – juanpa.arrivillaga Oct 25 '18 at 16:57

3 Answers3

3

Use ast.literal_eval to convert string representation to a list and get the first item:

import ast

str = "['A20150710', 1.0]"

print(ast.literal_eval(str)[0])
# A20150710
Austin
  • 25,142
  • 4
  • 21
  • 46
1

Split on , and remove punctuations

import string
str1 = "['A20150710', 1.0]"
str1=str1.split(',')[0]
str1.translate(None,string.punctuation) #'A20150710'
mad_
  • 7,844
  • 2
  • 22
  • 37
1

Use eval to parse the string, then fetch the information you want

str = "['A20150710', 1.0]"
eval(str)[0] # A20150710

!!!Be careful!!! Using eval is a security risk, as it executes arbitrary Python expressions

Andrei Cioara
  • 2,934
  • 3
  • 31
  • 52