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
  • 18,706
  • 61
  • 194
  • 336
  • 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
  • 24,608
  • 4
  • 20
  • 43
1

Split on , and remove punctuations

import string
str1 = "['A20150710', 1.0]"
str1=str1.split(',')[0]
str1.translate(None,string.punctuation) #'A20150710'
mad_
  • 7,475
  • 1
  • 18
  • 32
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,384
  • 2
  • 23
  • 46