# 示例代码:str函数在Python中的用法
# 1. 将其他类型转换为字符串
number = 123
string_number = str(number) # 将整数转换为字符串
print(f"整数 {number} 转换为字符串: {string_number}")
float_number = 3.14
string_float = str(float_number) # 将浮点数转换为字符串
print(f"浮点数 {float_number} 转换为字符串: {string_float}")
boolean_value = True
string_boolean = str(boolean_value) # 将布尔值转换为字符串
print(f"布尔值 {boolean_value} 转换为字符串: {string_boolean}")
# 2. 使用str.format()方法进行字符串格式化
name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# 3. 使用f-string(Python 3.6+)进行字符串格式化
formatted_f_string = f"My name is {name} and I am {age} years old."
print(formatted_f_string)
# 4. 使用str.join()方法连接多个字符串
words = ["Hello", "world", "from", "Python"]
joined_string = " ".join(words) # 使用空格连接列表中的字符串
print(joined_string)
# 5. 使用str.split()方法分割字符串
sentence = "This is a test sentence."
split_words = sentence.split() # 默认按空格分割
print(split_words)
# 6. 使用str.replace()方法替换字符串中的子串
original_string = "Hello, world!"
new_string = original_string.replace("world", "Python")
print(new_string)
str()
函数可以将整数、浮点数和布尔值等数据类型转换为字符串。str.format()
方法进行字符串格式化:通过占位符 {}
和 .format()
方法,可以在字符串中插入变量值。str.join()
方法连接多个字符串:可以将一个字符串列表合并成一个字符串,指定分隔符。str.split()
方法分割字符串:可以根据指定的分隔符将字符串拆分为列表,默认情况下按空格分割。str.replace()
方法替换字符串中的子串:可以将字符串中的某个子串替换为另一个子串。上一篇:find函数python
下一篇:python字符串类型
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站