파이썬 3에는 str.isidentifier
Python 2.6에서 Python isidentifer() 기능을 어떻게 얻을 수 있습니까?
등의 기능이 있습니다. 파이썬 2.6에서 비슷한 기능을 어떻게 얻을 수 있을까요?
파이썬 3에는 str.isidentifier
Python 2.6에서 Python isidentifer() 기능을 어떻게 얻을 수 있습니까?
등의 기능이 있습니다. 파이썬 2.6에서 비슷한 기능을 어떻게 얻을 수 있을까요?
re.match(r'[a-z_]\w*$', s, re.I)
해야합니다. 내가 아는 한 기본 제공 방법이 없습니다.
파이썬 < 3.0에서는 식별자에 유니 코드 문자를 사용할 수 없으므로 매우 쉽습니다. 즉, 작업을 수행해야합니다
import re
import keyword
def isidentifier(s):
if s in keyword.kwlist:
return False
return re.match(r'^[a-z_][a-z0-9_]*$', s, re.I) is not None
토큰 화 모듈 이름
지금까지import re, tokenize, keyword
re.match(tokenize.Name + '$', somestr) and not keyword.iskeyword(somestr)
이러한 목적으로 '^'+ 토큰 화. 이름 + '$'가 필요합니다. –
python 예약어를 추가하십시오. 나는 이것을 좋아합니다. –
@Douglas S.J. De Couto -'import keyword','keyword.iskeyword (astring)'을 사용하여 문자열이 키워드인지 확인 할 수 있습니다.이 문서의 [here] (http://docs.python.org/library/keyword.html)를 참조하십시오. # keyword.iskeyword). – Abbafei
좋은 답변이라고하는 정규 표현식을 정의합니다. 나는 이것을 이렇게 쓰고 싶다. 몇 가지 좋은 제안이 있었다 때문에 나는이 또 다른 균열을하기로 결정했습니다
def is_valid_keyword_arg(k):
"""
Return True if the string k can be used as the name of a valid
Python keyword argument, otherwise return False.
"""
# Don't allow python reserved words as arg names
if k in keyword.kwlist:
return False
return re.match('^' + tokenize.Name + '$', k) is not None
대문자 허용 필요. 위의 답변도 비슷한 문제가 있습니다. –
@Douglas : 그것은're.I' 플래그가있는 것입니다. – SilentGhost
. 나는 그들을 통합하려고 노력할 것이다. 다음은 Python 모듈로 저장하고 명령 행에서 직접 실행할 수 있습니다. 실행되면 함수를 테스트하므로 정확하게 정확합니다 (적어도 문서에서 기능을 보여주는 정도까지).
import keyword
import re
import tokenize
def isidentifier(candidate):
"""
Is the candidate string an identifier in Python 2.x
Return true if candidate is an identifier.
Return false if candidate is a string, but not an identifier.
Raises TypeError when candidate is not a string.
>>> isidentifier('foo')
True
>>> isidentifier('print')
False
>>> isidentifier('Print')
True
>>> isidentifier(u'Unicode_type_ok')
True
# unicode symbols are not allowed, though.
>>> isidentifier(u'Unicode_content_\u00a9')
False
>>> isidentifier('not')
False
>>> isidentifier('re')
True
>>> isidentifier(object)
Traceback (most recent call last):
...
TypeError: expected string or buffer
"""
# test if candidate is a keyword
is_not_keyword = candidate not in keyword.kwlist
# create a pattern based on tokenize.Name
pattern_text = '^{tokenize.Name}$'.format(**globals())
# compile the pattern
pattern = re.compile(pattern_text)
# test whether the pattern matches
matches_pattern = bool(pattern.match(candidate))
# return true only if the candidate is not a keyword and the pattern matches
return is_not_keyword and matches_pattern
def test():
import unittest
import doctest
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite())
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
test()
're.match'는 줄의 처음부터 일치합니다. – SilentGhost
: 내가 사용하고 무엇
import keyword
import re
def isidentifier(candidate):
"Is the candidate string an identifier in Python 2.x"
is_not_keyword = candidate not in keyword.kwlist
pattern = re.compile(r'^[a-z_][a-z0-9_]*$', re.I)
matches_pattern = bool(pattern.match(candidate))
return is_not_keyword and matches_pattern
모든 솔루션은 유니 코드를 지원하거나 파이썬 3에 실행하면 첫 번째 문자 에 숫자를 허용하지 않습니다 지금까지 제안했다.
편집 : 제안 된 솔루션은 Python 2에서만 사용해야하며 Python3에서는 isidentifier
을 사용해야합니다.
re.match(r'^\w+$', name, re.UNICODE) and not name[0].isdigit()
기본적으로, 그것은 뭔가 (번호 포함) (최소 1) 문자로 구성 여부를 테스트 한 다음 첫 번째 문자가 숫자가 아닌 것을 확인 : 여기 어디서든 작동합니다 솔루션입니다.
예 : 유니 코드 기호와 함께 작동하지 않습니다. ''éllo'' – Almar