1、字符串的定义

Python 中的字符串指的是由单个或多个字符组成的字符串,可以使用单引号(')或双引号(")来表示,也可以使用三引号(''' 或 """)来表示多行字符串。

2、字符串常用操作

Python 中常用的字符串操作有:

1、字符串的连接,可以使用 + 操作符连接字符串;

str1 = 'Hello'
str2 = 'World'
str3 = str1 + str2
print(str3)
Python

2、字符串的重复,可以使用 * 操作符来重复字符串;

str1 = 'Hello'
str2 = str1 * 3
print(str2)
Python

3、字符串的切片,可以使用 操作符来切片字符串;

str1 = 'Hello World'
str2 = str1[0:5]
print(str2)
Python

4、字符串的替换,可以使用 replace 方法替换字符串;

str1 = 'Hello World'
str2 = str1.replace('World', 'Python')
print(str2)
Python

5、字符串的查找,可以使用 find 方法查找字符串;

str1 = 'Hello World'
str2 = str1.find('World')
print(str2)
Python

3、字符串的格式化

Python 中可以使用 format 方法来格式化字符串,可以使用 {} 来指定要替换的字符串,可以使用 : 来指定替换的格式,如下:

str1 = 'Hello {}, your score is {:.2f}'
str2 = str1.format('Tom', 80.5678)
print(str2)
Python