[转载] 字符串太长 pep8_Python f字符串– PEP 498 –文字字符串插值

参考链接: 从Java中的字符串中删除前导零

字符串太长 pep8

 

  

  

 

 Python f-strings or formatted strings are the new way to format strings. This feature was introduced in Python 3.6 under PEP-498. It’s also called literal string interpolation.

  Python f字符串或格式化的字符串是格式化字符串的新方法。 此功能是在PEP-498下的Python 3.6中引入的。 也称为文字字符串插值 。  

  为什么我们需要F弦? (Why do we need f-strings?) 

 Python provides various ways to format a string. Let’s quickly look at them and what are the issues they have.

  Python提供了多种格式化字符串的方法。 让我们快速查看它们以及它们有什么问题。  

 

  

 % formatting – great for simple formatting but limited support for strings, ints, doubles only. We can’t use it with objects. %格式 -非常适合简单的格式设置,但仅对string ,ints和double的支持有限。 我们不能将其与对象一起使用。 Template Strings – it’s very basic. Template strings work with keyword arguments like dictionary only. We are not allowed to call any function and arguments must be strings. 模板字符串 –非常基本。 模板字符串仅可与关键字参数(例如字典)一起使用。 我们不允许调用任何函数,并且参数必须是字符串。 String format() – Python String format() function was introduced to overcome the issues and limited features of %-formatting and template strings. However, it’s too verbose. Let’s look at its verbosity with a simple example.>>> age = 4 * 10

>>> 'My age is {age}.'.format(age=age)

'My age is 40.' 字符串格式()– Python字符串格式()函数的引入是为了克服%格式和模板字符串的问题和有限的功能。 但是,它太冗长了。 让我们用一个简单的例子来看看它的详细程度。 

 Python f-strings works almost similar like format() function but removes all the verbosity that format() function has. Let’s see how easily we can format the above string using f-strings.

  Python f字符串的工作原理几乎类似于format()函数,但删除了format()函数具有的所有冗长性。 让我们看看使用f字符串格式化上述字符串的难易程度。  

 >>> f'My age is {age}'

'My age is 40.'

 Python f-strings is introduced to have minimal syntax for string formatting. The expressions are evaluated at runtime. If you are using Python 3.6 or higher version, you should use f-strings for all your string formatting requirements.

  引入Python f字符串是为了使字符串格式化的语法最少 。 在运行时对表达式求值。 如果您使用的是Python 3.6或更高版本,则应使用f-strings满足所有字符串格式要求。  

  Python f字符串示例 (Python f-strings examples) 

 Let’s look at a simple example of f-strings.

  让我们看一个简单的f字符串示例。  

 name = 'Pankaj'

age = 34

 

f_string = f'My Name is {name} and my age is {age}'

 

print(f_string)

print(F'My Name is {name} and my age is {age}')  # f and F are same

 

name = 'David'

age = 40

 

# f_string is already evaluated and won't change now

print(f_string)

 Output:

  输出:  

 

  

  

 

 My Name is Pankaj and my age is 34

My Name is Pankaj and my age is 34

My Name is Pankaj and my age is 34

 Python executes statements one by one and once f-string expressions are evaluated, they don’t change even if the expression value changes. That’s why in the above code snippets, f_string value remains same even after ‘name’ and ‘age’ variable has changed in the latter part of the program.

  Python会一一执行语句,并且一旦评估了f字符串表达式,即使表达式值更改,它们也不会更改。 这就是为什么在上面的代码段中,即使在程序的后半部分更改了“ name”和“ age”变量后,f_string值仍保持不变。  

  1.带表达式和转换的f字符串 (1. f-strings with expressions and conversions) 

 We can use f-strings to convert datetime to a specific format. We can also run mathematical expressions in f-strings.

  我们可以使用f字符串将日期时间转换为特定格式。 我们还可以在f字符串中运行数学表达式。  

 from datetime import datetime

 

name = 'David'

age = 40

d = datetime.now()

 

print(f'Age after five years will be {age+5}')  # age = 40

print(f'Name with quotes = {name!r}')  # name = David

print(f'Default Formatted Date = {d}')

print(f'Custom Formatted Date = {d:%m/%d/%Y}')

 Output:

  输出:  

 Age after five years will be 45

Name with quotes = 'David'

Default Formatted Date = 2018-10-10 11:47:12.818831

Custom Formatted Date = 10/10/2018

  2. f字符串支持原始字符串 (2. f-strings support raw strings) 

 We can create raw strings using f-strings too.

  我们也可以使用f字符串创建原始字符串。  

 print(f'Default Formatted Date:\n{d}')

print(fr'Default Formatted Date:\n {d}')

 Output:

  输出:  

 

  

  

 

 Default Formatted Date:

2018-10-10 11:47:12.818831

Default Formatted Date:\n 2018-10-10 11:47:12.818831

  3.具有对象和属性的f字符串 (3. f-strings with objects and attributes) 

 We can access object attributes too in f-strings.

  我们也可以在f字符串中访问对象属性。  

 class Employee:

    id = 0

    name = ''

 

    def __init__(self, i, n):

        self.id = i

        self.name = n

 

    def __str__(self):

        return f'E[id={self.id}, name={self.name}]'

 

 

emp = Employee(10, 'Pankaj')

print(emp)

 

print(f'Employee: {emp}\nName is {emp.name} and id is {emp.id}')

 Output:

  输出:  

 E[id=10, name=Pankaj]

Employee: E[id=10, name=Pankaj]

Name is Pankaj and id is 10

  4. f字符串调用函数 (4. f-strings calling functions) 

 We can call functions in f-strings formatting too.

  我们也可以用f字符串格式调用函数。  

 def add(x, y):

    return x + y

 

 

print(f'Sum(10,20) = {add(10, 20)}')

 Output: Sum(10,20) = 30

  输出: Sum(10,20) = 30  

  5.带空格的f字符串 (5. f-string with whitespaces) 

 If there are leading or trailing whitespaces in the expression, they are ignored. If the literal string part contains whitespaces then they are preserved.

  如果表达式中存在前导或尾随空格,则将其忽略。 如果文字字符串部分包含空格,则将保留它们。  

 >>> age = 4 * 20

>>> f'   Age = {  age   }  '

'   Age = 80  '

  6.带f字符串的Lambda表达式 (6. Lambda expressions with f-strings) 

 We can use lambda expressions insidef-string expressions too.

  我们也可以在字符串表达式内部使用lambda表达式 。  

 x = -20.45

print(f'Lambda Example: {(lambda x: abs(x)) (x)}')

 

print(f'Lambda Square Example: {(lambda x: pow(x, 2)) (5)}')

 Output:

  输出:  

 Lambda Example: 20.45

Lambda Square Example: 25

  7. f弦的其他示例 (7. f-strings miscellaneous examples) 

 Let’s look at some miscellaneous examples of Python f-strings.

  让我们看一些Python f字符串的其他示例。  

 print(f'{"quoted string"}')

print(f'{{ {4*10} }}')

print(f'{{{4*10}}}')

 Output:

  输出:  

 quoted string

{ 40 }

{40}

 That’s all for python formatted strings aka f-strings.

  这就是python格式的字符串,又称f字符串。  

 

  GitHub Repository.

  GitHub存储库中检出完整的python脚本和更多Python示例。 

 

 Reference: PEP-498, Official Documentation

  参考: PEP-498 , 官方文档  

 

  翻译自: https://www.journaldev.com/23592/python-f-strings-literal-string-interpolation

 

 字符串太长 pep8

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/540198.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

备忘(持续更新。。。)

1、在springmvc这个框架里面,创建新的业务逻辑层,dao、service层至少需要一个接口,项目才能跑起来 2、获取当前用户桌面路径 File desktopDir FileSystemView.getFileSystemView() .getHomeDirectory();String desktopPath desktopDir.getA…

[转载] 字符串操作截取后面的字符串_对字符串的5个必知的熊猫操作

参考链接: 修剪Java中的字符串(删除前导和尾随空格) 字符串操作截取后面的字符串 We have to represent every bit of data in numerical values to be processed and analyzed by machine learning and deep learning models. However, strings do not usually co…

更改域控制器的计算机名

林功能级别必须为Windows Server 2003及以上 1. netdom computername Server08-1.contoso.com /add:08Server1.contoso.com 2. netdom computername Server08-1.contoso.com /makeprimary:08Server1.contoso.com 3. Restart your computer 4. netdom computername 08Server1.co…

[转载] Google Java代码规范

参考链接: 使用Java计算文本文件txt中的行数/单词数/字符数和段落数 原文地址:https://google.github.io/styleguide/javaguide.html GIthub上GoogleCode风格的配置文件(支持Eclipse IDE和IntelliJ IDE):https://git…

SQL PASS西雅图之行——签证篇

本人有幸通过IT168&itpub的站庆活动http://www.itpub.net/thread-1716961-1-1.html,并应微软邀请参加了在西雅图举办的The Conference for SQL Server Professionals(简称SQL-PASS)。 SQL-PASS会议计划于2012年11月6日-9日举行&#xff0…

[转载] java8 lambda表达式 List转为Map

参考链接&#xff1a; 使用Lambda表达式检查字符串在Java中是否仅包含字母 public static void main(String[] args) { List<User> userList new ArrayList<User>(); User user0 new User("han1", "男1", 20); User user1 new User("…

11.python并发入门(part5 event对象)

一、引入event。 每个线程&#xff0c;都是一个独立运行的个体&#xff0c;并且每个线程的运行状态是无法预测的。 如果一个程序中有很多个线程&#xff0c;程序的其他线程需要判断某个线程的运行状态&#xff0c;来确定自己下一步要执行哪些操作。 threading模块中的event对象…

[转载] Java 将字符串首字母转为大写 - 利用ASCII码偏移

参考链接&#xff1a; 使用ASCII值检查Java中的字符串是否仅包含字母 将字符串name 转化为首字母大写。普遍的做法是用subString()取第一个字母转成大写再与之后的拼接&#xff1a; str str.substring(0, 1).toUpperCase() str.substring(1); 看到一种效率更高的做法&…

俞永福卸任阿里大文娱董事长,改任 eWTP 投资组长

两天前&#xff08;11月13日&#xff09;&#xff0c;阿里文娱董事长俞永福离职的消息&#xff0c;在互联网圈炸了锅。但很快&#xff0c;俞本人就在微博做了澄清&#xff0c;并称“永远幸福&#xff0c;我不会离开”。然而就在今天&#xff08;11月15日&#xff09;&#xff0…

[转载] java提取字符串中的字母数字

参考链接&#xff1a; 使用Regex检查字符串在Java中是否仅包含字母 String str "adsf adS DFASFSADF阿德斯防守对方asdfsadf37《&#xff1f;&#xff1a;&#xff1f;%#&#xffe5;%#&#xffe5;%#$%#$%^><?1234"; str str.replaceAll("[^a-zA-…

snort的详细配置

前一段一直在做snort入侵检测系统的安装以及配置&#xff0c;看了很多的网上资料&#xff0c;也算是总结了下前辈的经验吧。需要的软件包&#xff1a;1、httpd-2.2.6.tar.gz2、mysql-5.1.22-rc-linux-i686-icc-glibc23.tar.gz3、php-5.2.4.tar.bz24、acid-0.9.6b23.tar.gz5、ad…

[转载] Java:获取数组中的子数组的多种方法

参考链接&#xff1a; Java中的数组Array 我的个人博客&#xff1a;zhang0peter的个人博客 Java&#xff1a;从一个数组中创建子数组 使用Arrays.copyOfRange函数 Arrays.copyOfRange支持&#xff1a;boolean[]&#xff0c; byte[] &#xff0c;char[]&#xff0c;double…

[转载] Java中Array(数组)转List(集合类)的几种方法

参考链接&#xff1a; Java中的数组类Array 1、循环。新建List类&#xff0c;循环填充。 2、利用Arrays类的静态方法asList()。 Arrays.asList(T[])返回Arrays类的一个内部内List(T)&#xff0c;此类继承自AbstractList&#xff0c;不可增删。若想要一个可以增删的List类&am…

Linux查看系统cpu个数、核心书、线程数

Linux查看系统cpu个数、核心书、线程数 现在cpu核心数、线程数越来越高&#xff0c;本文将带你了解如何确定一台服务器有多少个cpu、每个cpu有几个核心、每个核心有几个线程。 查看物理cpu个数 cat /proc/cpuinfo |grep "physical id"|sort |uniq|wc -l 查看核…

[转载] java中数组的反射的探究

参考链接&#xff1a; Java中的反射数组类reflect.Array 数组的反射有什么用呢&#xff1f;何时需要使用数组的反射呢&#xff1f;先来看下下面的代码&#xff1a; Integer[] nums {1, 2, 3, 4}; Object[] objs nums; //这里能自动的将Integer[]转成Object[] Object obj n…

防火墙iptables之常用脚本

防火墙iptables之常用脚本 转自&#xff1a;http://zhujiangtao.blog.51cto.com/6387416/1286490 标签&#xff1a;防火墙 主机 1。不允许别人ping我的主机&#xff0c;但是我可以ping别人的主机 #!/bin/bash iptables -F iptables -X iptables -Z modprobe ip_tables modprobe…

[转载] java中50个关键字以及各自用法大全

参考链接&#xff1a; Java中的默认数组值 关键字和保留字的区别 正确识别java语言的关键字&#xff08;keyword&#xff09;和保留字&#xff08;reserved word&#xff09;是十分重要的。Java的关键字对java的编译器有特殊的意义&#xff0c;他们用来表示一种数据类型&…

NFS 共享存储

服务器客户端yum -y install rpcbind nfs-utils 服务器 vim /etc/exports /data 192.168.10.0/24(rw,sync,no_root_squash) * ro # 只读权限 * rw # 读写权限 * sync # 同步&#xff0c;数据更安全&#xff0c;速度慢 * async #异步&#xff0c;速度快&#xff0c;效率高&a…

[转载] Java中的final变量、final方法和final类

参考链接&#xff1a; Java中的final数组 &#xff5c; Final arrays 1、final变量 final关键字可用于变量声明&#xff0c;一旦该变量被设定&#xff0c;就不可以再改变该变量的值。通常&#xff0c;由final定义的变量为常量。例如&#xff0c;在类中定义PI值&#xff0c;可…

Linux基础篇_01_计算机概论

学习资料&#xff1a;《鸟哥的Linux私房菜&#xff08;基础篇&#xff09;》部分&#xff1a;Linux的规划与安装 时间&#xff1a;20130225 学习笔记&#xff1a;计算机定义&#xff1a;接受使用者输入指令与数据&#xff0c; 经由中央处理器的数学与逻辑单元运算处理后&#x…