Can I import Python's 3.6's formatted string literals (f-strings) into older 3.x, 2.x Python?

前端 未结 8 1321
臣服心动
臣服心动 2020-12-15 02:27

The new Python 3.6 f-strings seem like a huge jump in string usability to me, and I would love to jump in and adopt them whole heartedly on new projects which might be runni

相关标签:
8条回答
  • 2020-12-15 03:20

    I just wrote a back-port compiler for f-string, called f2format. Just as you requests, you may write f-string literals in Python 3.6 flavour, and compile to a compatible version for end-users to run, just like Babel for JavaScript.

    f2format provides an intelligent, yet imperfect, solution of a back-port compiler. It shall replace f-string literals with str.format methods, whilst maintaining the original layout of source code. You can simply use

    f2format /path/to/the/file_or_directory

    which will rewrite all Python files in place. For instance,

    var = f'foo{(1+2)*3:>5}bar{"a", "b"!r}boo'

    will be converted to

    var = ('foo{:>5}bar{!r}boo').format(((1+2)*3), ("a", "b"))

    String concatenation, conversion, format specification, multi-lines and unicodes are all treated right. Also, f2format will archive original files in case there're any syntax breaches.

    0 讨论(0)
  • 2020-12-15 03:22

    Using dict() to hold name-value pairs

    • In addition to the approaches mentioned elsewhere in this thread (such as format(**locals()) ) the developer can create one or more python dictionaries to hold name-value pairs.

    • This is an obvious approach to any experienced python developer, but few discussions enumerate this option expressly, perhaps because it is such an obvious approach.

    • This approach is arguably advantageous relative to indiscriminate use of locals() specifically because it is less indiscriminate. It expressly uses one or more dictionaries a namespace to use with your formatted string.

    • Python 3 also permits unpacking multiple dictionaries (e.g., .format(**dict1,**dict2,**dict3) ... which does not work in python 2.7)

      ## init dict
      ddvars = dict()
    
      ## assign fixed values
      ddvars['firname']   =   'Huomer'
      ddvars['lasname']   =   'Huimpson'
      ddvars['age']       =   33
      pass
    
      ## assign computed values
      ddvars['comname']   =   '{firname} {lasname}'.format(**ddvars)
      ddvars['reprself']  =   repr(ddvars)
      ddvars['nextage']   =   ddvars['age'] + 1
      pass
    
      ## create and show a sample message
      mymessage = '''
      Hello {firname} {lasname}!
      Today you are {age} years old.
      On your next birthday you will be {nextage} years old!
      '''.format(**ddvars)
    
      print(mymessage)
    
    0 讨论(0)
提交回复
热议问题