有趣的F-String
在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的更多相关文章
- File(File f, String child) File(String parent, String child)
(转载)File(File f, String child) 根据f 抽象路径名和 child 路径名字符串创建一个新 File 实例. f抽象路径名用于表示目录,child 路径名字符串用于表示目录 ...
- codeforces 825F F. String Compression dp+kmp找字符串的最小循环节
/** 题目:F. String Compression 链接:http://codeforces.com/problemset/problem/825/F 题意:压缩字符串后求最小长度. 思路: d ...
- 透过WinDBG的视角看String
摘要 : 最近在博客园里面看到有人在讨论 C# String的一些特性. 大部分情况下是从CODING的角度来讨论String. 本人觉得非常好奇, 在运行时态, String是如何与这些特性联系上的 ...
- 如果你也会C#,那不妨了解下F#(1):F# 数据类型
本文链接:http://www.cnblogs.com/hjklin/p/fs-for-cs-dev-1.html 简单介绍 F#(与C#一样,念作"F Sharp")是一种基于. ...
- STL string的构造函数
前几天在网上,一位网友问我几个问题如下: , 'A'); string S1 = "abcdefg"; , ); ); cout << "s0 = " ...
- 【Codeforces710F】String Set Queries (强制在线)AC自动机 + 二进制分组
F. String Set Queries time limit per test:3 seconds memory limit per test:768 megabytes input:standa ...
- String类的构造方法详解
package StringDemo; //String类的构造方法详解 //方法一:String(); //方法二:String(byte[] bytes) //方法三:String (byte[] ...
- Java基础之String、StringBuffer、StringBuilder
1:String类:字符串(重点) (1)多个字符组成的一个序列,叫字符串. 生活中很多数据的描述都采用的是字符串的.而且我们还会对其进行操作. 所以,java就提供了这样的一个类供我们使用. (2) ...
- C++ string 用法详解
/////////////////////////////////////////////////////////////////////////////////// 任何人对本文进行引用都要标明作者 ...
- String类的常用方法
package stringUse; public class StringUse { public static void main(String[] args) { //获取 //indexOf, ...
随机推荐
- Linux 修改本地时间 (centos为例)
1. tzselect [root@xxxx etc]# tzselect --- 选择时区命令 Please identify a location so that time zone rules ...
- AtCoDeerくんと選挙速報 / AtCoDeer and Election Report AtCoder - 2140 (按比例扩大)
Problem Statement AtCoDeer the deer is seeing a quick report of election results on TV. Two candidat ...
- Spring 使用AOP——xml配置
目录 AOP介绍 Spring进行2种实现AOP的方式 导入jar包 基于schema-based方式实现AOP 创建前置通知 创建后置通知 修改Spring配置文件 基于schema-based方式 ...
- form表单中新增button按钮,点击按钮表单会进行提交
原生button控件,在非ie浏览器下,如果不指定type,默认为submit类型.如果不想自动提交表单,指定type=“button”
- Lodop、c-lodop注册与角色简短问答
注册与角色:参考http://www.c-lodop.com/demolist/t1.html参考链接里的三种场景,是哪种角色.客户端访问网站后用自己的打印机打印.是客户端本地打印角色.IP和域名注册 ...
- 电脑浅色显示器不显示怎么办,如何用PS去除logo底色
本人买了新电脑后,虽然电脑显示器颜色也不错,就是刚买回来提示个true color没正确安装,我也没在意,因为感觉电脑显示方面还是不错的,后来定做安装程序用logo图的时候,有个浅色背景色,自己没看出 ...
- LODOP直线px转换mm变斜线
LODOP中打印项顶边距左边距,宽高,可以选择的单位很多,详细可在LODOP官网下载参考LODOP技术手册. 关于LODOP打印直线和虚线,可查看本博客相关博文:Lodop如何打印直线.Lodop打印 ...
- Python学习之路——函数的参数分类
今日内容 '''实参:调用函数,在括号内传入的实际值,值可以为常量.变量.表达式或三者的组合*****形参:定义函数,在括号内声明的变量名,用来接受外界传来的值''''''注:形参随着函数的调用 ...
- Virtual Box虚拟机安装Ubuntu16.04以及整理的一些基本操作
事先声明,参考自:https://www.cnblogs.com/wyt007/p/9856290.html 撰写此文,纯属是为了便利以后换电脑重装. 转载请注明地址:https://www.cnbl ...
- [CTSC2018]暴力写挂
题目描述 www.lydsy.com/JudgeOnline/upload/201805/day1(1).pdf 题解 首先来看这个我们要最大化的东西. deep[u]+deep[v]-deep[lc ...