个性化阅读
专注于IT技术分析

Python字符串插值用法示例

字符串插值是将变量的值替换为字符串中的占位符的过程, 听起来像是字符串串联!但是不用+或串联方法。

让我们看看在Python中字符串插值的工作方式。

  • %格式
  • Str.format()
  • f-strings
  • 模板字符串

%格式

这是Python提供的一项功能, 可以通过%操作员。这类似于打印C中的样式函数

例子:

# Python program to demonstrate
# string interpolation
  
  
n1 = 'Hello'
n2 = 'srcmini'
  
# for single substitution
print ( "Welcome to % s" % n2)
  
# for single and multiple substitutions () mandatory
print ( "% s ! This is % s." % (n1, n2))

输出如下

Welcome to srcmini
Hello! This is srcmini.

假设它只是一个复杂的版本, 但是如果我们有很多变量要替换为字符串, 我们可以使用它, 因为我们并不总是希望使用(“字符串” + variable +” string” + variable + variable +” string “)的表示形式。为此, 我们可以选择%-格式化。

注意:进一步了解%格式点击这里.

Str.format()

str.format()是Python3中的字符串格式化方法之一, 它允许多次替换和值格式化。通过此方法, 我们可以通过位置格式将字符串中的元素连接起来。

例子:

# Python program to demonstrate
# string interpolation
  
  
n1 = 'Hello'
n2 = 'srcmini'
  
# for single substitution
print ( 'Hello, {}' . format (n1))
  
# for single or multiple substitutions
# let's say b1 and b2 are formal parameters 
# and n1 and n2 are actual parameters
print ( "{b1}! This is {b2}." . format (b1 = n1, b2 = n2))
  
# else both can be same too
print ( "{n1}! This is {n2}." . format (n2 = n2, n1 = n1))

输出如下

Hello, Hello
Hello! This is srcmini.
Hello! This is srcmini.

注意:进一步了解str.format() 点击这里.

f-strings

PEP 498引入了一种新的字符串格式化机制, 称为”文字字符串插值”, 或更常见的是f-strings(因为字符串文字前的前导f字符)。 f字符串背后的想法是使字符串插值更简单。

要创建f字符串, 请在字符串前添加字母” f”。字符串本身的格式可以与你使用的格式几乎相同str.format()。 F字符串为将python表达式嵌入字符串文字中进行格式化提供了一种简洁方便的方法。

例子:

# Python program to demonstrate
# string interpolation
  
  
n1 = 'Hello'
n2 = 'srcmini'
  
# f tells Python to restore the value of two
# string variable name and program inside braces {}
print (f "{n1}! This is {n2}" )
  
# inline arithmetic
print (f "(2 * 3)-10 = {(2 * 3)-10}" )

输出如下

Hello! This is srcmini
(2*3)-10 = -4

注意:进一步了解f-strings点击这里.

字符串模板类

在字符串模块中, 模板类允许我们为输出规范创建简化的语法。该格式使用由$组成的占位符名称, 并带有有效的Python标识符(字母数字字符和下划线)。用大括号括起来的占位符允许其后跟更多字母数字字母, 中间没有空格。编写$$将创建一个转义的$:

例子:

# Python program to demonstrate
# string interpolation
  
  
from string import Template
  
n1 = 'Hello'
n2 = 'srcmini'
  
# made a template which we used to 
# pass two variable so n3 and n4 
# formal and n1 and n2 actual
n = Template( '$n3 ! This is $n4.' )
  
# and pass the parameters into the template string.
print (n.substitute(n3 = n1, n4 = n2))

输出如下

Hello Hello! This is srcmini.

注意:进一步了解String Template类点击这里.

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(1)
未经允许不得转载:srcmini » Python字符串插值用法示例

评论 抢沙发

评论前必须登录!