• 技术文章 >常见问题 >Python常见问题

    python的str函数为什么不能用

    silencementsilencement2019-10-25 16:51:57原创4523

    str函数是Python的内置函数,它将参数转换成字符串类型,即人适合阅读的形式。

    其语法格式为

    1

    str(object)

    返回值:

    返回object的字符串形式

    使用示例

    1. 无参调用

    当str()函数的参数都省略时,函数返回空字符串。这种情况常用来创建空字符串或者初始化字符串变量。

    1

    2

    >>> str()

    ''

    2. 不省略参数

    str函数将整数、浮点数、列表、元组、字典和集合转换为字符串类型

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    >>> str(-23) #整数转换为字符串

    '-23'

      

    >>> str(1.3e2) #浮点数转换为字符串

    '130.0'

      

    >>> a_list = [12, '-23.1', 'Python']

    >>> str(a_list)  #列表转换为字符串

    "[12, '-23.1', 'Python']"

    >>> str(a_list)[0]

    '['

      

    >>> a_tuple = (23, '9we', -8.5)

    >>> str(a_tuple)  #元组转换为字符串

    "(23, '9we', -8.5)"

      

    >>> a_dictionary = {'Huawei':'China', 'Apple':'USA'}

    >>> str(a_dictionary)  #字典转换为字符串

    "{'Huawei': 'China', 'Apple': 'USA'}"

    >>> str(a_dictionary)[10]

    ' '

      

    >>> a_set = {'China', 'Japan', 'UK'}

    >>> str(a_set)  #集合转换为字符串

    "{'Japan', 'UK', 'China'}"

    注意

    1

    2

    将列表、元组、字典和集合转换为字符串后,包裹列表、元组、字典和集合的'['、']'、'('、')'、'{'、'}',以及列表、元组、

    字典和集合中的元素分隔符',',和字典中键值对':'也都转换成了字符串,是转换后字符串的一部分。

    更多学习内容,请点击Python学习网

    专题推荐:str
    上一篇:python的return语法错误怎么解决 下一篇:python怎么创建新对象

    相关文章推荐

    • python distribute是什么• python的str是什么类型

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网