> 文章列表 > str在python中用法

str在python中用法

str在python中用法

在Python中,`str`函数用于将其他数据类型转换为字符串类型。以下是`str`函数的一些基本用法:

1. 无参调用 :

```pythonstr() # 返回空字符串```

2. 转换不同类型的数据 :

```pythonstr(-520) # 将整数转换为字符串str(2.4e012) # 将浮点数转换为字符串str([1, 2, 3]) # 将列表转换为字符串str({\'a\': 1, \'b\': 2}) # 将字典转换为字符串```

3. 字符串操作 :

连接 :

```pythonstr1 = \"Hello\"str2 = \"World\"print(str1 + \" \" + str2) # 输出 \"Hello World\"```

复制 :

```pythonstr = \"abc\"print(str * 3) # 输出 \"abcabcabc\"```

索引 :

```pythonstr = \"abcdefg\"print(str) # 输出 \"c\"```

切片 :

```pythonstr = \"abcdefg\"print(str[0:3]) # 输出 \"abc\"print(str[3:5:2]) # 输出 \"ace\"```

4. 自定义字符串表示 :

如果需要自定义一个类的字符串表示形式,可以重写`__str__`方法:

```pythonclass Person: def __init__(self, name=\"Tom\", age=10): self.name = name self.age = age def __str__(self): return f\"Your name is: {self.name}, and you are {self.age} years old.\"person = Person()print(person) # 输出 \"Your name is: Tom, and you are 10 years old.\"```

5. 特殊字符处理 :

转义字符:

```pythonstr_2 = r\"python\\nclass\" # 输出 \"python\\nclass\"```

行尾续行:

```pythonstr_2 = \"python\\nclass\" # 输出 \"python\\nclass\"```

6. 字符串运算 :

拼接:

```pythonstr1 = \"Hello\"str2 = \"World\"print(str1 + \" \" + str2) # 输出 \"Hello World\"```

重复输出:

```pythonstr = \"abc\"print(str * 3) # 输出 \"abcabcabc\"```

`str`函数可以作用于任何数据类型的任何对象,包括`None`,返回其字符串表示形式。需要注意的是,在拼接不同类型的对象时,可能需要先进行类型转换

其他小伙伴的相似问题:

养殖行业门户网