파이썬 문자열 자르기
조회수 2326회
파이썬 유저입니다.
예를 들어 a="apple,banana,cow" 라는 문자열이 있으면
print_1="apple" print_2="banana" print_3="cow"
이런 식으로 저장하는 코드를 어떻게 짤 수 있을까요?
(초보입니다. 잘 부탁드립니다.)
2 답변
-
파이썬은 변수관리를 dict 타입으로 관리합니다.
dict 타입으로 관리한다는 사실이 중요합니다.
a = "apple,banana,cow" varTemplate = "print_{}" for i, v in enumerate(a.split(',')): globals()[varTemplate.format(i)] = v print_0 Out[29]: 'apple' print_1 Out[30]: 'banana' print_2 Out[31]: 'cow'
-
a="apple,banana,cow" print_1, print_2, print_3 = a.split(',') print_1 Out[11]: 'apple' print_2 Out[12]: 'banana' print_3 Out[13]: 'cow'
댓글 입력