And*_*ndy 0 python string python-3.x
我在这样的字符串中有一个 Authorization 标头:
Bearer [myawesometoken]
Run Code Online (Sandbox Code Playgroud)
我不想使用空格字符进行标记,因为我想要求字符串“Bearer”位于字符串的开头
从字符串中只返回令牌的pythonic方法是什么?
有没有像 PHP 这样的正则表达式匹配函数preg_match()?这会是pythonic的方式吗?
我认为最 Pythonic 的方法是使用和字符串切片的内置startswith方法:str
PREFIX = 'Bearer '
def get_token(header):
if not header.startswith(PREFIX):
raise ValueError('Invalid token')
return header[len(PREFIX):]
Run Code Online (Sandbox Code Playgroud)
但是,我更愿意str.partition将标头标记为 3 元组:
PREFIX = 'Bearer'
def get_token(header):
bearer, _, token = header.partition(' ')
if bearer != PREFIX:
raise ValueError('Invalid token')
return token
Run Code Online (Sandbox Code Playgroud)