Python字符串连接教程

字符串连接是Python编程语言中一个重要而流行的话题。Python提供了不同的函数和操作符,以便以不同的方式连接字符串。字符串连接也称为连接字符串或粘合字符串。

null

Python字符串连接方式

在Python中,可以使用不同的方法和运算符连接两个或多个字符串。下面是如何连接两个或多个字符串或字符串变量的列表。

  • +操作员
  • 连续放线
  • *操作员
  • join()方法
  • format()方法

+操作员

连接两个或多个字符串最常用的方法之一是使用加号或+运算符。+运算符也提供了比其他方法更高的可读性运算符也用于字符串值和字符串变量。在下面的示例中,我们将定义多个字符串,然后用+运算符连接它们。

a = "Python"b = "Wisetut"c = "Windows"print( a + b )print( a + b + c )

我们还可以使用+运算符来连接两个或多个字符串值或文字,如下所示。

a = "Python" + "Wisetut"print(a)b = "Python" + "Wisetut" + "Windows"print(b)print( "Python" + "Wisetut" )print( "Python" + "Wisetut" + "Windows" )

连续放线

Python还提供了一种有趣的方法来连接两个或多个字符串,而不使用任何操作符或方法。只要将两个或多个字符串与一个或多个空格分隔符放在一起,就可以连接给定的字符串。

a = "Python" "Wisetut"
print(a)
#Output#Pytho
nWisetutb = "Python" "Wisetut"  "Windows"
print(b)
#Output
#Pytho
nWisetutWindows
print( "Python" "Wisetut" )
#Output
#Pytho
nWisetut
print( "Python" "Wisetut" "Windows" )#Output
#Pytho
nWisetutWindows

*操作员

即使它不是一个完整的串联运算符,*运算符也可以用来对给定的字符串进行乘法。在数学术语中,*等于像3*2这样的多重串联意味着将3求和2次。

a = "Python" * 2print(a)
#Output
#Pytho
nPytho
n

a = "Python" * 5
print(a)
#Output
#Pytho
nPytho
n
Pytho
nPytho
nPytho
n


print( "Python" * 2 )
#Output
#Pytho
nPytho
n

print( "Python" * 5
 )
#Output
#Pytho
nPytho
n
Pytho
nPytho
nPytho
n

join()方法

Python提供了一个名为 join() 由字符串数据结构提供。join()方法将连接所提供列表中的每个元素。在加入元素之前,每个元素都将转换为一个字符串。

names = [ "Python" , "Windows" , "Linux" ]print("".join(names))#Output#Python,Windows,Linux

我们还可以在连接操作期间提供一些字符串或字符来放置在列表项之间。例如,逗号可以用作分隔符,其中列表中的每个元素都将与逗号放在一起。

names = [ "Python" , "Windows" , "Linux" ]

print(",".join(names))#Output#Python,Windows,Linux

或者,我们可以指定一个单词作为分隔符,同时将列表项作为字符串连接起来。在下面的示例中,我们将使用字符串 tect 作为连接分隔符。

names = [ "Python" , "Windows" , "Linux" ]

print("tect ".join(names))
#Output
#Pythontect Windowstect Linuxtect

到目前为止,我们已经从字符串值调用了join()方法。我们还可以通过字符串变量调用join()方法,该变量的值将用作分隔符字符串。

names = [ "Python" , "Windows" , "Linux" ]
a = "tect"
print(a.join(names))
#Output
#Pythontect Windowstect Linuxtect

format()方法

Python字符串变量和值或Python字符串类型提供了format()方法,用于格式化字符串。format()方法提供高级功能,可用于连接多个字符串。通常,要连接的字符串作为format()方法的参数提供,如下语法所示。

"{} {} {}".format( STRING1 , STRING2 , STRING3 )
  • {}是一个locaters,这里提供的字符串参数将依次放置
  • 字符串参数用于向concatanate提供字符串。它们可以是1或更多。

让我们举一些例子来学习format()方法来连接字符串。

a = "Python"b = "Windows"c = "Linux"x = "{} {} {}".format( a , b , c )print(x)y = "{} {} {}".format( a , "Windows" , "Linux" )
print(y)z = "{} and {} and {}".format( a , b , "Linux" )
print(z)

我们还可以使用数字字符串描述符,通过提供参数索引来更改它们的位置。第一个参数用{0}表示,第二个参数用{1},第三个参数{3}等表示。

a = "Python"

b = "Windows"

c = "Linux"

x = "{0} {1} {2}".format( a , b , c )
print(x)


y = "{2} {1} {0}".format( a , "Windows" , "Linux" )
print(y)


z = "{2} and {0} and {1}".format( a , b , "Linux" )
print(z)
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享