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,227
  • 87
  • 254
  • 417
  • 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,759
  • 4
  • 25
  • 48
1

Split on , and remove punctuations

import string
str1 = "['A20150710', 1.0]"
str1=str1.split(',')[0]
str1.translate(None,string.punctuation) #'A20150710'
mad_
  • 8,121
  • 2
  • 25
  • 40
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
  • 3,404
  • 5
  • 34
  • 62