https://www.pydanny.com/python-f-string-are-fun.html

在Python3.6的发布中,我们看到他们采纳了字符串字面量插值,或者用更通俗的说法:f-string

最开始叫我用的时候,我是犹豫的,因为我们已经有很多字符串工具了:

one, two = 1, 2
_format = '{},{}'.format(one, two)
_percent = '%s,%s' % (one, two)
_concatenation = str(one) + ',' + str(two)
_join = ','.join([str(one), str(two)]) assert _format == _percent == _concatenation == _join == _fstring

加入f-string之后,也不见得特别有用:

_fstring = f'{one},{two}'

assert _format == _percent == _concatenation == _join == _fstring

最开始的时候我很怀疑,但是之后我将f-string应用到一个现实的项目。现在,真香。。。f-string可以让之前版本中,python那些很繁琐的写法简化。

我感觉真香的原因是因为,f-string更加的简洁,同时也更加地易读:

_fstring = f'Total: {one + two}'  # Go f-string!
_format = 'Total: {}'.format(one + two)
_percent = 'Total: %s' % (one + two)
_concatenation = 'Total: ' + str(one + two)
assert _fstring == _format == _percent == _concatenation

F-String 让人上瘾

初看起来,f-string只是python的一个小改动,但是实际用下来会发现,这个改动对语言的可读性的加强是巨大的。

现在我对f-string上瘾了。让我使用3.6以前版本的Python,我会总感觉少了什么。

Okay,享受这个上瘾的感觉吧!f-string是个很好的东西。

一个工具脚本的例子

我们最近发布了<<Two Scoops of Django 1.11>>,它是使用Latex写的。就像很多编程数据一样,我们把书里面的代码都整理进了一个repo,供读者使用。

不过,在我们校正代码高亮之后,我们需要重头提取这些代码。这是一个繁琐的工作,然后我使用Python3.6中的f-string,用30分钟的时间写了下面的脚本,完成了工作:

"""Two Scoops of Django 1.11 Code Extractor"""
import os
import shutil
from glob import glob try:
shututl.rmtree('code')
print('Remove old code directory')
except FileNotFoundError:
pass
os.mkdir('code')
print('Created new code directory') STAR = '*' LANGUAGES = """LEGAL TEXT GOES HERE""" LANGUAGE_START = {
'\\begin{python}': '.py',
'\\begin{badpython}': '.py',
'\\begin{django}': '.html',
'\\begin{baddjango}': '.html',
'\\begin{plaintext}': '.txt',
'\\begin{badplaintext}': '.txt',
'\\begin{sql}': '.sql',
'\\begin{makefile}': '',
'\\begin{json}': '.json',
'\\begin{bash}': '.txt',
'\\begin{xml}': '.html',
} LANGUAGE_END = {x.replace('begin', 'end'): y for x, y in LANGUAGE_START.items()} def is_example(line, SWITCH):
for key in SWITCH:
if line.strip().startswith(key):
return SWITCH[key]
return None def makefilename(chapter_num, in_example):
return f"code/chapter_{chapter_num}_example_{str(example_num).zfill(2)}{in_example}" if __name__ == '__main__':
in_example = False
starting = False
for path in glob('chapters/*.tex'):
try:
chapter_num = int(path[9:11])
chapter_num = path[9:11]
except ValueError:
if not path.lower().startswith('appendix'):
print(f'{STAR*40}\n{path}\n{STAR*40}')
continue
example_num = 1
with open(path) as f:
lines = (x for x in f.readlines())
for line in lines:
if starting:
# Crazy long string interpolation that should probably
# be broken up but remains because it's easy for me to read
filename = f'code/chapter_{chapter_num}_example_{str(example_num).zfill(2)}{in_example}'
dafile = open(filename, 'w')
if in_example in ('.py', '.html'):
dafile.write(f'"""\n{LEGALESE}"""\n\n')
else:
dafile.write(f'{LEGALESE}\n{STAR*20}\n\n')
print(filename)
if not in_example:
mime = None
in_example = is_example(line, LANGUAGE_START)
if in_example:
starting = True
continue
mime = is_example(line, LANGUAGE_END)
starting = False
if mime:
print(mime)
in_example = False
example_num += 1
dafile.close()
else:
dafile.write(line)

有趣的F-String的更多相关文章

  1. File(File f, String child) File(String parent, String child)

    (转载)File(File f, String child) 根据f 抽象路径名和 child 路径名字符串创建一个新 File 实例. f抽象路径名用于表示目录,child 路径名字符串用于表示目录 ...

  2. codeforces 825F F. String Compression dp+kmp找字符串的最小循环节

    /** 题目:F. String Compression 链接:http://codeforces.com/problemset/problem/825/F 题意:压缩字符串后求最小长度. 思路: d ...

  3. 透过WinDBG的视角看String

    摘要 : 最近在博客园里面看到有人在讨论 C# String的一些特性. 大部分情况下是从CODING的角度来讨论String. 本人觉得非常好奇, 在运行时态, String是如何与这些特性联系上的 ...

  4. 如果你也会C#,那不妨了解下F#(1):F# 数据类型

    本文链接:http://www.cnblogs.com/hjklin/p/fs-for-cs-dev-1.html 简单介绍 F#(与C#一样,念作"F Sharp")是一种基于. ...

  5. STL string的构造函数

    前几天在网上,一位网友问我几个问题如下: , 'A'); string S1 = "abcdefg"; , ); ); cout << "s0 = " ...

  6. 【Codeforces710F】String Set Queries (强制在线)AC自动机 + 二进制分组

    F. String Set Queries time limit per test:3 seconds memory limit per test:768 megabytes input:standa ...

  7. String类的构造方法详解

    package StringDemo; //String类的构造方法详解 //方法一:String(); //方法二:String(byte[] bytes) //方法三:String (byte[] ...

  8. Java基础之String、StringBuffer、StringBuilder

    1:String类:字符串(重点) (1)多个字符组成的一个序列,叫字符串. 生活中很多数据的描述都采用的是字符串的.而且我们还会对其进行操作. 所以,java就提供了这样的一个类供我们使用. (2) ...

  9. C++ string 用法详解

    /////////////////////////////////////////////////////////////////////////////////// 任何人对本文进行引用都要标明作者 ...

  10. String类的常用方法

    package stringUse; public class StringUse { public static void main(String[] args) { //获取 //indexOf, ...

随机推荐

  1. 基于 WebGL 3D 的 HTML5 档案馆可视化管理系统

    前言 档案管理系统是通过建立统一的标准以规范整个文件管理,包括规范各业务系统的文件管理的完整的档案资源信息共享服务平台,主要实现档案流水化采集功能.为企事业单位的档案现代化管理,提供完整的解决方案,档 ...

  2. 基于 HTML5 结合互联网+的电力接线图

    前言 “互联网+”思维让数据的搜集和获取更加便捷,并且随着大数据的深度开发和应用,数据分析预测对于提升用户体验有非常重要的价值,同时也为不同行业.不同领域的合作提供了更广阔的空间.传统的发电企业是一个 ...

  3. 爬虫之selenium模块

    Selenium 简介 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题 selenium本质是通过驱动浏览器,完全模拟 ...

  4. openstack搭建之-neutron配置(11)

    一.base节点设置 mysql -u root -proot CREATE DATABASE neutron; GRANT ALL PRIVILEGES ON neutron.* TO 'neutr ...

  5. powershell 函数, foreach中格式化

    function testArg { $n = 1; if($args.Count -eq 0) { "No arg!" } else { $args | foreach {&qu ...

  6. IO复用,AIO,BIO,NIO,同步,异步,阻塞和非阻塞 区别参考

    参考https://www.cnblogs.com/aspirant/p/6877350.html?utm_source=itdadao&utm_medium=referral IO复用,AI ...

  7. ABP中的模块初始化过程(一)

    在总结完整个ABP项目的结构之后,我们就来看一看ABP中这些主要的模块是按照怎样的顺序进行加载的,在加载的过程中我们会一步步分析源代码来进行解释,从而使自己对于整个框架有一个清晰的脉络,在整个Asp. ...

  8. iOS高德地图让指定区域或者点显示在屏幕中间

    对于高德地图也是一个新手,很多功能看文档,问技术 或者高德群里讨论  群号:204668425 在我们需求中绘制的有 圆 折线 不规则图形 方式,打开地图指定的绘制图形置于屏幕中间 1.首先创建一个数 ...

  9. python之正则表达式和re模块一

    摘要:正则表达式 re模块 一.正则表达式:只和字符串打交道,是一种用来约束字符串的规则 1.应用场景: 1,判断某一个字符串是否符合规则:注册页-判断手机号.身份证号 是否合法 注册某个账号的时候, ...

  10. AJAX初识(原生JS版AJAX和Jquery版AJAX)

    一.什么是JSON 1.介绍 JSON独立于语言,是一种与语言无关的数据格式. JSON指的是JavaScript对象表示法(JavaScript Object Notation) JSON是轻量级的 ...