字符串是由字符组成的有序集合,用于表示文本信息。在Python中,字符串是一种基本的数据类型,可以用单引号(' ')、双引号(" ")或三引号(''' '''或""" """)来创建。
以上就是Python中字符串的基本概念和操作。希望对你有所帮助!
-
创建字符串:
使用单引号或双引号创建字符串:
str1 = 'hello, world' str2 = "hello, world"
-
使用三引号创建多行字符串:
复制代码运行
str3 = ''' hello, world '''
-
字符串操作:
(1) 访问字符串中的字符:
可以通过索引(从0开始)访问字符串中的字符:
复制代码运行
str = 'hello, world' print(str[0]) # 输出 'h'
(2) 字符串切片:
可以使用切片操作符获取字符串的子串:
复制代码运行
str = 'hello, world' print(str[0:5]) # 输出 'hello'
(3) 字符串拼接:
使用加号(+)将两个字符串连接在一起:
复制代码运行
str1 = 'hello, ' str2 = 'world' str3 = str1 + str2 print(str3) # 输出 'hello, world'
(4) 字符串重复:
使用乘号(*)重复字符串:
复制代码运行
str = 'hello, world' print(str * 3) # 输出 'hello, worldhello, worldhello, world'
(5) 字符串分割:
使用split()方法将字符串分割成列表:
复制代码运行
str = 'hello, world' print(str.split(',')) # 输出 ['hello', ' world']
(6) 字符串替换:
使用replace()方法替换字符串中的子串:
复制代码运行
str = 'hello, world' print(str.replace('world', 'Python')) # 输出 'hello, Python'
(7) 字符串大小写转换:
使用upper()和lower()方法将字符串转换为大写或小写:
复制代码运行
str = 'Hello, World' print(str.upper()) # 输出 'HELLO, WORLD' print(str.lower()) # 输出 'hello, world'
(8) 字符串查找:
使用find()方法查找子串在字符串中的位置:
复制代码运行
str = 'hello, world' print(str.find('world')) # 输出 7
(9) 字符串长度:
使用len()函数获取字符串的长度:
复制代码运行
str = 'hello, world' print(len(str)) # 输出 12
(10) 字符串格式化:
使用format()方法或f-string将变量插入到字符串中:
复制代码运行
name = 'Tom' age = 18 print('My name is {} and I am {} years old.'.format(name, age)) # 输出 'My name is Tom and I am 18 years old.' print(f'My name is {name} and I am {age} years old.') # 输出 'My name is Tom and I am 18 years old.'