当前位置:  首页>> 技术小册>> Python合辑5-格式化字符串

21、处理多行f-string(换行符的处理)
可以用换行符\n来打印多行文本。

  1. >>> multi_line = (f'R: {color["R"]}\nG: {color["G"]}\nB: {color["B"
  2. ...: ]}\n')
  3. >>> multi_line
  4. 'R: 123\nG: 145\nB: 255\n'
  5. >>> print(multi_line)
  6. R: 123
  7. G: 145
  8. B: 255

还可以用三引号实现多行字符串。这样不单能增加换行符,还能有Tab。

  1. >>> other = f"""R:{color["R"]}
  2. ...: G:{color["G"]}
  3. ...: B:{color["B"]}
  4. ...:"""
  5. >>> print(other)
  6. R: 123
  7. G: 145
  8. B: 255

用 Tab 的代码样例

  1. >>> other = f'''
  2. ...:this is an example
  3. ...:
  4. ...:^Iof color {color["R"]}
  5. ...:
  6. ...: '''
  7. >>> other
  8. '\nthis is an example\n\n\tof color 123\n \n'
  9. >>> print(other)
  10. this is an example
  11. of color123
  12. >>>