在Python中,`str`是一个内置的字符串类型,用于表示和操作文本数据。以下是一些常见的`str`用法:
创建字符串
使用单引号或双引号创建字符串:
s1 = 'Hello, World!'
s2 = "Hello, World!"
使用三引号创建多行字符串:
s3 = """Hello,
World!"""
访问字符串中的字符
使用索引操作符(`[]`)访问字符串中的字符:
first_char = s1 输出:H
字符串切片
使用切片操作符(`:`)获取字符串的子串:
sub_str = s1[7:12] 输出:World!
字符串拼接
使用加号(`+`)拼接字符串:
new_str = s1 + " Welcome!" 输出:Hello, World! Welcome!
字符串格式化
使用`format()`方法格式化字符串:
name = "Alice"
message = "Hello, {}!".format(name) 输出:Hello, Alice!
字符串方法
字符串对象有许多内置方法,如`find()`, `replace()`, `split()`等:
length = len(s1) 输出:13
substring = s1.find("World") 输出:7
new_str = s1.replace("World", "Python") 输出:Hello, Python!
其他有用的函数
`str()`函数将参数转换成字符串类型:
str_num = str(-23) 输出:-23
str_list = str([1, 2, 3]) 输出:'[1, 2, 3]'
`__str__()`函数用于定义对象的字符串表示形式:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name: {self.name}, Age: {self.age}"
p = Person("Alice", 25)
print(p) 输出:Name: Alice, Age: 25
以上是Python中`str`的一些基本用法。