`
zsjg13
  • 浏览: 144948 次
  • 性别: Icon_minigender_1
  • 来自: 安徽
社区版块
存档分类
最新评论

Converting Between Simple Types

 
阅读更多

    除了 string formating 特性,Python还提供了许多函数用于 numerical 和 string 类型之间的转换。

 

1、Converting to numerical types

    函数 int、long、float、complex,以及ord 都是将数据转换成 numerical 类型。

 

(1)int (x[, radix])

    使用一个 string 和一个可选的 base,将一个 number 或 string 转换成一个 integer:

>>> int(‘15’)

15

>>> int(‘15’,16) # In hexadecimal, sixteen is written “10”

21

    待转换的字符串必须是一个合法的整数,转换字符串 3.5 就会失败。int 函数可以将其他 numbers 转换成 integers:

>>> int(3.5)

3

>>>int(10L)

10

    int 函数会去掉一个 number 的小数部分。要得到 最接近的 integer,就要用 round 函数。

 

(2)long(x[, radix])

    可以将一个字符串或另一个 number转换成一个 long integer,也可以包含一个base:

>>> long('125')

125L

>>> long(17.6)

17L

>>> long('1E', 16)

30L

 

(3)float(x)

>>> float(12.1)

12.1

>>> float(10L)

10.0

>>> int(float("3.5")) # int("3.5") is illegal

3

The exception is with complex numbers; use the abs function to “convert” a

complex number to a floating-point number.

 

(4)round(num[,digits])

    四舍五入一个浮点数为一个拥有指定小数位的一个 number:

>>> round(123.5678, 3)

123.568

>>> round(123.5678)

124.0

>>> round(123.4)

123.0

 

(5)complex(real[, imaginary])

    可以将一个字符串或 number转成一个复数,它还带一个可选的imaginary部分,如果没有提供的话:

>>> complex('2+5j')

(2+5j)

>>> complex('2')

(2+0j)

>>> complex(6L, 3)

(6+3j)

 

(6)ord(ch)

    参数是一个字符,返回的是该字符对应的 ASCII 或 Unicode值

>>> ord(u'a')

97

>>> ord('b')

98

 

 

2、Converting to strings

    以下函数将 numbers 转换成 字符串。

 

(1)chr (x) and unichr (x)

     将参数代表的 ASCII 或 Unicode 值 转成一个字符:

>>> chr(98)

‘b’

 

(2)oct (x) and hex (x)

    将 numbers 转换成八进制和16进制字符串表示:

>>> oct(123)

'0173'

>>> hex(123)

'0x7b'

 

(3)str (obj)

    返回对象的一个可打印的字符串版本值:

>>> str(5)

'5'

>>> str(5.5)

‘5.5’

>>> str(3+2j)

‘(3+2j)’

    当使用 print 语句时,Python会就会调用该函数。

 

(4)repr(obj)

    repr 和 str 类似,except that it tries to return a string version of the object that is valid Python syntax。对于简单的数据类型,它俩的输出常常是一样的。 

它的一个简写方式是将待转换的对象放到``号之间。

>>> a = 5

>>> ‘Give me ‘ + a # Can’t add a string and an integer!

Traceback (innermost last):

File “<interactive input>”, line 1, in ?

TypeError: cannot add type “int” to string

>>> ‘Give me ‘ + `a` # Convert to a string on-the-fly.

‘Give me 5’

 

    从 2.1 版开始,str 和 repr 会原样显示 newlines 和 其他转义序列,而不是显示它们的 ASCII code:

>>> 'Hello\nWorld'

'Hello\nWorld'

 

    当以交互式方式使用 Python interpreter, Python 会调用 repr 来显示对象。你可以让它使用一个不同的函数,那就要先修改 sys.displayhook 的值:

>>> 5.3

5.2999999999999998  # The standard representation is ugly.

>>> def printstr(s):

...   print str(s)

>>> import sys

>>> sys.displayhook = printstr

>>> 5.3

5.3  # A more human-friendly format

 

The sys.displayhook feature is new in Python 2.1.

分享到:
评论

相关推荐

    Professional C# 3rd Edition

    Communication between Contexts 462 Remote Objects, Clients, and Servers 462 Remote Objects 462 A Simple Server 464 A Simple Client 465 .NET Remoting Architecture 466 Channels 466 Formatters 470 ...

    Addison.Wesley.C++.by.Dissection.2002.pdf

    - **Simple Types:** Explains primitive data types such as integers, floats, and characters. - **Initialization:** Describes different methods of initializing variables. - **The Traditional Conversions...

    The Art of Assembly Language Programming

    QWORD, and TBYTE Variables 5.3.5 - Declaring Floating Point Variables with REAL4, REAL8, and REAL10 5.4 - Creating Your Own Type Names with TYPEDEF 5.5 - Pointer Data Types 5.6 - ...

    C Programming

    - **From Problem to Program**: This discusses the process of converting a problem statement into a program, including understanding the problem, designing an algorithm, coding, testing, and debugging....

    python3.6.5参考手册 chm

    Deprecated functions and types of the C API Deprecated Build Options Removed API and Feature Removals Porting to Python 3.6 Changes in ‘python’ Command Behavior Changes in the Python API ...

    Itanium Architecture For Programmers

    Parallels Between Integer and Floating-Point Instructions Section 8.2. Representations of Floating-Point Values Section 8.3. Copying Floating-Point Data Section 8.4. Floating-Point Arithmetic ...

    Addison.Wesley.Ruby.Phrasebook.Sep.2008

    Converting Between Types** 这部分内容主要讲解了如何在Ruby中进行类型转换。Ruby是一种动态类型的编程语言,支持多种数据类型之间的相互转换。常见的转换包括整数到浮点数、字符串到整数或浮点数等。例如,可以...

    Unreal Engine 4.X By Example

    This project involves creating a character that can hop between barrels in a level. - **Creating Our Character**: Designing a character actor and adding necessary components. - **Bringing Our ...

    IOS5 Programming Cookbook

    - **Implicit Casting**: In ARC, implicit casting occurs when the compiler automatically casts between compatible types to resolve type mismatches. ### 18. Delegating Tasks with Protocols (Page 63) -...

    Lerner -- Python Workout. 50 Essential Exercises -- 2020.pdf

    - **Objective:** Develop a simple number guessing game where the computer selects a random number and the user tries to guess it. - **Key Concepts:** - Random number generation using the `random` ...

    BobBuilder_app

    Twitter Digg Facebook Del.icio.us Reddit Stumbleupon Newsvine Technorati Mr....Database » Database » Other databasesLicence...In v2.3 a single simple change of converting internal classes ...

    ZendFramework中文文档

    7.5.6. Route Types 7.5.6.1. Zend_Controller_Router_Route 7.5.6.1.1. 变量缺省 7.5.6.1.2. 变量请求 7.5.6.2. Zend_Controller_Router_Route_Static 7.5.6.3. Zend_Controller_Router_Route_Regex 7.5.7. ...

    C++标准库(第二版)英文版.pdf

    3.1.14 New FundamentalData Types . . . . . . . . . . . . . . . . . . . . . . . 33 3.2 Old “New” Language Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 3.2.1 ...

    php.ini-development

    The syntax of the file is extremely simple. Whitespace and lines ; beginning with a semicolon are silently ignored (as you probably guessed). ; Section headers (e.g. [Foo]) are also silently ignored,...

Global site tag (gtag.js) - Google Analytics