Python3 字符串
Python3 字符串
Python3中字符串是不可变的序列类型,用于表示文本数据。本篇技术文档将介绍Python3字符串的常用操作和函数。
创建字符串
在Python3中创建字符串有多种方法:
- 单引号(’)或双引号(")括起来的一段文本;
- 三个单引号(’’’)或双引号(""")括起来的多行文本;
- str构造函数将其他对象转换为字符串;
- 使用 + 运算符连接多个字符串。
# 创建普通字符串
string1 = 'Hello, world!'
string2 = "I'm a string."
# 创建多行字符串
string3 = '''Hello,
world!'''
string4 = """I'm a
multi-line string."""
# 转换为字符串
number = 123
string5 = str(number)
# 连接多个字符串
string6 = 'Hello, ' + 'world!'
访问字符串
Python3字符串是一个字符序列,可以通过下标访问每个字符。字符串的下标从0开始,负数下标表示倒数第n个字符。
string = 'Hello, world!'
print(string[0]) # H
print(string[7]) # w
print(string[-1]) # !
字符串切片
字符串切片指通过指定起止下标获取子字符串,其语法为:
string[start:stop:step]
其中,start表示起始下标(默认为0),stop表示终止下标(默认为字符串长度),step表示步长(默认为1)。
string = 'Hello, world!'
print(string[0:5]) # Hello
print(string[:5]) # Hello
print(string[7:]) # world!
print(string[3:8:2]) # 'l,o'
字符串函数
Python3字符串内置了丰富的函数,以下是常用的函数:
len
返回字符串的长度。
string = 'Hello, world!'
print(len(string)) # 13
count
返回指定子字符串在字符串中出现的次数。
string = 'Hello, world!'
print(string.count('l')) # 3
find 和 index
返回指定子字符串在字符串中第一次出现的位置,如果未出现则返回-1(find),或者抛出异常(index)。
string = 'Hello, world!'
print(string.find('l')) # 2
print(string.index('l')) # 2
print(string.find('x')) # -1
print(string.index('x')) # Raises ValueError
replace
将指定子字符串替换为另一个字符串,并返回新的字符串,如果指定的子字符串不存在,则返回原字符串。
string = 'Hello, world!'
new_string = string.replace('Hello', 'Hi')
print(new_string) # Hi, world!
lower 和 upper
将字符串分别转换为全小写和全大写,返回新的字符串。
string = 'Hello, world!'
print(string.lower()) # hello, world!
print(string.upper()) # HELLO, WORLD!
strip
去除字符串首尾的空白字符。
string = ' Hello, world! '
print(string.strip()) # Hello, world!
split
按照指定分隔符将字符串分割成子串,并返回子串列表。
string = 'Hello, world!'
items = string.split(', ')
print(items) # ['Hello', 'world!']