Programing

파이썬에서 문자열을 어떻게 분할하고 구문 분석 할 수 있습니까?

lottogame 2020. 8. 17. 09:33
반응형

파이썬에서 문자열을 어떻게 분할하고 구문 분석 할 수 있습니까?


이 문자열을 파이썬으로 분할하려고합니다. 2.7.0_bf4fda703454

_왼쪽에있는 값을 사용할 수 있도록 해당 문자열을 밑줄로 분할하고 싶습니다 .


"2.7.0_bf4fda703454".split("_") 문자열 목록을 제공합니다.

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

이것은 모든 밑줄 에서 문자열을 분할합니다 . 첫 번째 분할 후 중지하려면을 사용하십시오 "2.7.0_bf4fda703454".split("_", 1).

문자열에 밑줄이 포함되어 있다는 사실을 알고 있다면 LHS와 RHS를 별도의 변수로 풀 수도 있습니다.

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

대안은를 사용하는 것 partition()입니다. 사용법은 두 개 대신 세 개의 구성 요소를 반환한다는 점을 제외하면 마지막 예와 유사합니다. 주요 이점은 문자열에 구분 기호가 포함되어 있지 않아도이 메서드가 실패하지 않는다는 것입니다.


Python 문자열 구문 분석 연습

공백에서 문자열을 분할하고, 목록을 가져오고, 유형을 표시하고, 출력합니다.

el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"

>>> mylist = mystring.split(" ")

>>> print type(mylist)
<type 'list'>

>>> print mylist
['What', 'does', 'the', 'fox', 'say?']

나란히 두 개의 구분 기호가있는 경우 빈 문자열로 간주됩니다.

el@apollo:~/foo$ python
>>> mystring = "its  so   fluffy   im gonna    DIE!!!"

>>> print mystring.split(" ")
['its', '', 'so', '', '', 'fluffy', '', '', 'im', 'gonna', '', '', '', 'DIE!!!']

밑줄로 문자열을 분할하고 목록에서 다섯 번째 항목을 가져옵니다.

el@apollo:~/foo$ python
>>> mystring = "Time_to_fire_up_Kowalski's_Nuclear_reactor."

>>> mystring.split("_")[4]
"Kowalski's"

여러 공간을 하나로 축소

el@apollo:~/foo$ python
>>> mystring = 'collapse    these       spaces'

>>> mycollapsedstring = ' '.join(mystring.split())

>>> print mycollapsedstring.split(' ')
['collapse', 'these', 'spaces']

Python의 split 메소드에 매개 변수를 전달하지 않으면 문서에 다음같이 표시됩니다 . "연속적인 공백의 실행은 단일 구분자로 간주되며 문자열에 선행 또는 후행 공백이있는 경우 결과는 시작 또는 끝에 빈 문자열을 포함하지 않습니다."

모자 소년을 붙잡고 정규 표현식을 구문 분석하십시오.

el@apollo:~/foo$ python
>>> mystring = 'zzzzzzabczzzzzzdefzzzzzzzzzghizzzzzzzzzzzz'
>>> import re
>>> mylist = re.split("[a-m]+", mystring)
>>> print mylist
['zzzzzz', 'zzzzzz', 'zzzzzzzzz', 'zzzzzzzzzzzz']

정규 표현식 "[AM] +"수단 소문자가 a관통 m하는 하나 이상의 시간 구분자로 일치 일어난다. re가져올 라이브러리입니다.

또는 항목을 한 번에 하나씩 자르려면 :

el@apollo:~/foo$ python
>>> mystring = "theres coffee in that nebula"

>>> mytuple = mystring.partition(" ")

>>> print type(mytuple)
<type 'tuple'>

>>> print mytuple
('theres', ' ', 'coffee in that nebula')

>>> print mytuple[0]
theres

>>> print mytuple[2]
coffee in that nebula

If it's always going to be an even LHS/RHS split, you can also use the partition method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS) if the separator is found, and (original_string, '', '') if the separator wasn't present:

>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')

>>> "shazam".partition("_")
('shazam', '', '')

참고URL : https://stackoverflow.com/questions/5749195/how-can-i-split-and-parse-a-string-in-python

반응형