str的python用法_python中str

str的python用法_python中str在 Python 中 str 是一个内置的字符串类型 用于表示和操作文本数据 以下是一些常见的 str 用法 创建字符串 使用单引号或双引号创建字符串 pythons1 Hello World s2 Hello World 使用三引号创建多行字符串 pythons3 Hello World 访问字符串中的字符

在Python中,`str`是一个内置的字符串类型,用于表示和操作文本数据。以下是一些常见的`str`用法:

创建字符串

使用单引号或双引号创建字符串:

python

s1 = 'Hello, World!'

s2 = "Hello, World!"

使用三引号创建多行字符串:

python

s3 = """Hello,

World!"""

访问字符串中的字符

使用索引操作符(`[]`)访问字符串中的字符:

python

first_char = s1 输出:H

字符串切片

使用切片操作符(`:`)获取字符串的子串:

python

sub_str = s1[7:12] 输出:World!

字符串拼接

使用加号(`+`)拼接字符串:

python

new_str = s1 + " Welcome!" 输出:Hello, World! Welcome!

字符串格式化

使用`format()`方法格式化字符串:

python

name = "Alice"

message = "Hello, {}!".format(name) 输出:Hello, Alice!

字符串方法

字符串对象有许多内置方法,如`find()`, `replace()`, `split()`等:

python

length = len(s1) 输出:13

substring = s1.find("World") 输出:7

new_str = s1.replace("World", "Python") 输出:Hello, Python!

其他有用的函数

`str()`函数将参数转换成字符串类型:

python

str_num = str(-23) 输出:-23

str_list = str([1, 2, 3]) 输出:'[1, 2, 3]'

`__str__()`函数用于定义对象的字符串表示形式:

python

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`的一些基本用法。

编程小号
上一篇 2026-03-19 10:20
下一篇 2026-03-19 10:16

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/71477.html