Does python support character type?

前端 未结 3 1348
天涯浪人
天涯浪人 2021-01-17 19:21

When I am checking with data types I wonder why a char value is returning as string type.

Please see my input and output.

Input:

<         


        
相关标签:
3条回答
  • 2021-01-17 19:48

    There is a bytes type which may be analogous depending on why you are asking.

    >>> b'a'
    => b'a'
    

    https://docs.python.org/3/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit

    0 讨论(0)
  • 2021-01-17 19:51

    No.

    Python does not have a character or char type. All single characters are strings with length one.

    0 讨论(0)
  • 2021-01-17 19:53

    There is no built-in type for character in Python, there are int, str and bytes. If you intend to user character, you just can go with str of length 1.

    Note that Python is weakly and dynamically typed, you do not need to declare type of your variables.

    All string you create using quote ', double quote " and triple quote """ are string (unicode):

    type("x")
    str
    

    When invoking built-in function type, it returns a type object representing the type of your variable:

    type(type("x"))
    type
    

    Integer and character do have mapping function (encoding), natively the sober map is ASCII, see chr and ord builti-in functions.

    type(123)
    int
    
    type(chr(65))
    str
    
    type(ord("x"))
    int
    

    If you must handle special characters that are not available in default charset, you will have to consider encoding:

    x = "é".encode()
    b'\xc3\xa9'
    

    The function encode, convert your sting into bytes and can be decoded back:

    x.decode()
    'é'
    

    Method encode and decode belongs respectively to object str and bytes.

    0 讨论(0)
提交回复
热议问题