Python基础-字符串拼接

目录

一、连接字符“+”

二、连接字符“join”

三、连接字符“format”

四、f字符串


    在Python中,字符串拼接是非常常见的应用,常见的有以下四种:

一、连接字符“+”

        两个数字相加会得到数量上的累加,但两个字符串相加是在第一个字符的结尾追加第二个字符。

>>> a = "Hello"
>>> b = " world!"
>>> print(a+b)
Hello world!

二、连接字符“join”

        语法:str.join(iterable)

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

返回一个用“str”连接起iterable各元素的字符串,iterable中的元素必须为字符串类型,否则会抛TypeError异常。

>>> print(" ".join(["Hello", "world!"]))
Hello world!
>>> 
>>> 
>>> 
>>> print(":".join(["Weight", "300g"]))
Weight:300g
>>>
>>> seqs = ["apple", "banana", "pear"]
>>> print(",".join([i for i in seqs]))
apple,banana,pear
>>> 
>>>
>>> print(",".join([i for i in range(10)]))
Traceback (most recent call last):
  File "", line 1, in 
TypeError: sequence item 0: expected str instance, int found

三、连接字符“format”

        语法:str.format(*args**kwargs)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

执行一个字符串格式化操作,在str中使用{}作为占位符,返回一个用*args**kwargs填充花括号的str。

#使用可变参数*args
>>> "This is {}'s dog".format("Alice")
"This is Alice's dog"
>>> 
>>> 
>>> "This isn't {}'s dog, it's {}'s".format("Alice", "Bob")
"This isn't Alice's dog, it's Bob's"
>>> 
>>> 
>>> "This isn't {0}'s dog, it's {1}'s".format("Alice", "Bob")
"This isn't Alice's dog, it's Bob's"

#使用关键字参数**kwargs
>>> "This isn't {name1}'s dog, it's {name2}'s".format(name1="Alice", name2="Bob")
"This isn't Alice's dog, it's Bob's"

>>> "This isn't {name[0]}'s dog, it's {name[1]}'s".format(name=["Alice", "Bob"])
"This isn't Alice's dog, it's Bob's"

四、f字符串

        f-string,格式化字符串常量。

>>> name="Nancy"
>>> age=6
>>> print(f'{name} is {age} years old.')
Nancy is 6 years old.
>>> 

注:推荐使用f-string,其运行速度更快。

你可能感兴趣的:(python,python)