美文网首页
python字符串格式化 f_string

python字符串格式化 f_string

作者: 乌溜溜的黑眼猪 | 来源:发表于2019-07-29 16:59 被阅读0次

    写python的数据库查询时,遇到了这样的语句
    按照过去的习惯,会写成

    query_like = 'SELECT from_user_id AS from_user_id, target_user_id AS target_user_id, 1 AS level FROM ' \
    'user_like WHERE from_user_id = "{}"'.format(user_id)
    

    两个引号丑陋不堪,format写起来也麻烦

    发现了pep498

    query_like = f'SELECT from_user_id AS from_user_id, target_user_id AS target_user_id, 1 AS level FROM ' \
    f'user_like WHERE from_user_id = {user_id!r}'
    

    更好的方式

    query_like = f'SELECT from_user_id AS from_user_id, target_user_id AS target_user_id, 1 AS level FROM ' \
    f'user_like WHERE from_user_id = {repr(user_id)}'
    
            engine = create_engine(
                f'mysql+pymysql://{self.user}:{self.passwd}@{self.host}:{self.port}/{self.db}')
    

    不要清晰太多

    相关文章

      网友评论

          本文标题:python字符串格式化 f_string

          本文链接:https://www.haomeiwen.com/subject/vhtirctx.html