python中strip_python中str的用法举例

python中strip_python中str的用法举例在 Python 中 str 是一个内置函数 用于将其他数据类型转换为字符串类型 以下是 str 函数的一些常见用法 字符串拼接 pythonstr1 Hello str2 World str3 str1 str2 使用加号运算符拼接字符串 print str3 输出 Hello World 类型转换 pythonnum

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

字符串拼接

 str1 = "Hello" str2 = "World" str3 = str1 + " " + str2 使用加号运算符拼接字符串 print(str3) 输出:Hello World 

类型转换

 num = 1234 str_num = str(num) 将整数转换为字符串 print(str_num, type(str_num)) 输出:1234 
  
    
   float_num = 3.1415 str_float = str(float_num) 将浮点数转换为字符串 print(str_float, type(str_float)) 输出:3.1415 
  
    
   

列表、组、字典和集合转换为字符串

 a_list = [12, -23.1, "Python"] str_list = str(a_list) 将列表转换为字符串 print(str_list) 输出:'[12, -23.1, 'Python']' a_tuple = (23, "9we", -8.5) str_tuple = str(a_tuple) 将组转换为字符串 print(str_tuple) 输出:'(23, '9we', -8.5)' a_dictionary = {"Huawei": "China", "Apple": "USA"} str_dict = str(a_dictionary) 将字典转换为字符串 print(str_dict) 输出:"{'Huawei': 'China', 'Apple': 'USA'}" a_set = {"China", "Japan", "UK"} str_set = str(a_set) 将集合转换为字符串 print(str_set) 输出:"{'China', 'Japan', 'UK'}" 

自定义对象的字符串表示

 class 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." tom = Person() print(tom) 输出:Your name is: tom, and you are 10 years old 

字符串格式化

 name = "Alice" age = 25 message = f"Hello, {name}! You are {age} years old." print(message) 输出:Hello, Alice! You are 25 years old 

字符串操作

 s = "Hello, World!" print(s) 输出:H print(s[7:12]) 输出:World! print(len(s)) 输出:13 

以上是`str`函数的一些基本用法,它可以帮助你在Python中方便地处理和操作字符串数据

编程小号
上一篇 2025-05-28 15:49
下一篇 2025-06-08 07:49

相关推荐

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