在Python中,`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, {}!"
formatted_message = message.format(name) 输出:Hello, Alice!
字符串方法
字符串对象有许多内置方法,如`len()`、`find()`、`replace()`等:
length = len(s1) 输出:13
substring = s1.find("World") 输出:7
new_str = s1.replace("World", "Python") 输出:Hello, Python!
str函数
`str()`函数用于将其他数据类型转换为字符串:
num = 1234
str_num = str(num) 输出:'1234'
自定义字符串表示
可以通过重写`__str__`方法来自定义对象的字符串表示形式:
class Person(object):
def __init__(self, name="tom", age=10):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
person = Person()
print(person) 输出:Person(name=tom, age=10)
以上是Python中`str`类型的一些基本用法。