두부찌개 파이썬( Tofusoup python)

블로그 이미지

tofusoup429

파이썬에 대한 정보를 공유하는 개인 블로그입니다.

'Python'에 해당되는 글 1건

제목 날짜
  • ast module for converting a List-type-string into a real python list 2017.05.07

ast module for converting a List-type-string into a real python list

Regular Python 2017. 5. 7. 09:16

The 'literal_eval()' function in module ast, which stands for Abstract Syntax Trees, is pretty useful when you want to turn "a string-formatted-list" into "a real list".


For example, you have a String aString = "['a','b','c']" and you want aString to be a real list, ['a','b','c'] . That is when you want to use the the 'literal_eval()' in ast module. It's a internal module so you do not need to install it additionally.


Example of Usage

Let me show you simple examples of how to use it.

import ast

aString="[3,4,2,'efe',3]"
aList=ast.literal_eval(aString)

First I defined a list-formatted-string and I want to revert it to a real python list, aList.

print(aList)
>> [3, 4, 2, 'efe', 3]
print(alist[1])
>> 4

Boom. It works.


It also works when a list-format string contains dictionaries-format string such as bString="[{'1':'a'},{'2':'b'}]"

import ast

bString = "[{'1':'a'},{'2':'b'}]"
bList = ast.literal_eval(bString)
print(bList)
>> [{'1': 'a'}, {'2': 'b'}]
print(bList[1])
>> {'2': 'b'}
print(bList[1]['2'])
>> b

Boom. It also works.


The strings were converted into real lists and the dictionaries seamlessly.

Hope this one helps

'Regular Python' 카테고리의 다른 글

파이썬 format을 이용해 초간단하게 1000의 단위마다 콤마 붙이기 (Putting comma every 3 digit in python)  (0) 2017.12.06
secrets 모듈을 사용해 리스트에서 무작위 item 추출하는 방법 (Extracting a random member from a list)  (0) 2017.12.02
Posted by tofusoup429
이전페이지 다음페이지
블로그 이미지

파이썬에 대한 정보를 공유하는 개인 블로그입니다.

by tofusoup429

공지사항

    최근...

  • 포스트
  • 댓글
  • 트랙백
  • 더 보기

태그

  • kivy
  • Python
  • AST
  • 키비
  • converting stringto list
  • GUI
  • 파이썬

글 보관함

«   2025/09   »
일 월 화 수 목 금 토
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

링크

카테고리

Python (9)
Regular Python (3)
Django Python (1)
Configuration (2)
Kivy Project (0)
project1. TimerApp (0)
기타 (2)

카운터

Total
Today
Yesterday
방명록 : 관리자 : 글쓰기
tofusoup429's Blog is powered by daumkakao
Skin info material T Mark3 by 뭐하라
favicon

두부찌개 파이썬( Tofusoup python)

파이썬에 대한 정보를 공유하는 개인 블로그입니다.

  • 태그
  • 링크 추가
  • 방명록

관리자 메뉴

  • 관리자 모드
  • 글쓰기
  • Python (9)
    • Regular Python (3)
    • Django Python (1)
    • Configuration (2)
    • Kivy Project (0)
      • project1. TimerApp (0)
    • 기타 (2)

카테고리

PC화면 보기 티스토리 Daum

티스토리툴바