Python Learning note Five: numbers and strings

Source: Internet
Author: User
Tags printable characters square root string methods

The data type is not allowed to change, which means that if you change the value of the numeric data type, the memory space will be redistributed.

Python Numeric type conversions
int (x [, Base]) converts x to         an integer  long (x [, Base]) converts X to        a long integer,  float (x) converts               x to a floating-point number  complex (real [, IMAG])  create a complex  str (x) to                 convert object x to String  repr (x) to                convert object x to expression string  eval (str)              Used to calculate a valid Python expression in a string, and returns an object  tuple (s) converts the               sequence s to a tuple list  (s) to                convert the sequence s to a listing  chr (x)                 Converts an integer to a character  UNICHR (x)              converts an integer to a Unicode character,  Ord (x)                 converts a character to its integer value,  hex (x)                 Converts an integer to a hexadecimal string  Oct (x)                 converts an integer to an octal string  
Python math functions
function return value (description)
ABS (x) Returns the absolute value of a number, such as ABS (-10) returns 10
Ceil (x) Returns the top integer of a number, such as Math.ceil (4.1) returns 5
CMP (x, y) If x < y returns 1, if x = = y returns 0, if x > y returns 1
EXP (x) Returns the x power of E (ex), such as MATH.EXP (1) returns 2.718281828459045
Fabs (x) Returns the absolute value of a number, such as Math.fabs (-10) returns 10.0
Floor (x) Returns the lower integer of a number, such as Math.floor (4.9) returns 4
Log (x) If Math.log (MATH.E) returns 1.0,math.log (100,10) returns 2.0
LOG10 (x) Returns the logarithm of x with a base of 10, such as MATH.LOG10 (100) returns 2.0
Max (x1, x2,...) Returns the maximum value of a given parameter, which can be a sequence.
Min (x1, x2,...) Returns the minimum value for a given parameter, which can be a sequence.
MODF (x) Returns the integer portion of x and the fractional part, the two-part numeric symbol is the same as x, and the integer part is represented by a floating-point type.
Pow (x, y) The value after the x**y operation.
Round (x [, N]) Returns the rounded value of the floating-point number x, if given an n value, that represents the digits rounded to the decimal point.
sqrt (x) Returns the square root of the number x, the number can be negative, and the return type is real, such as MATH.SQRT (4) returns 2+0J

PythonRandom number function

Random numbers can be used in mathematics, games, security and other fields, but also often embedded in the algorithm to improve the efficiency of the algorithm and improve the security of the program.

Python contains the following common random number functions:

function Description
Choice (seq) Pick an element randomly from the elements of the sequence, such as Random.choice (range (10)), and randomly pick an integer from 0 to 9.
Randrange ([Start,] stop [, step]) Gets a random number in the collection that increments by the specified cardinality from the specified range, and the base default value is 1
Random () Randomly generates the next real number, which is within the [0,1] range.
Seed ([x]) Changes the seeding seed of the random number generator. If you don't know how it works, you don't have to specifically set Seed,python to help you choose Seed.
Shuffle (LST) Randomly sort all elements of a sequence
Uniform (x, Y) Randomly generates the next real number, which is within the [x, Y] range.

Python Trigonometric functions

Python includes the following trigonometric functions:

function Description
ACOs (x) Returns the inverse cosine radian value of x.
ASIN (x) Returns the arc value of the arc sine of X.
Atan (x) Returns the arc tangent value of x.
Atan2 (y, x) Returns the inverse tangent value of the given X and Y coordinate values.
COS (x) Returns the cosine of the arc of X.
Hypot (x, y) Returns Euclidean norm sqrt (x*x + y*y).
Sin (x) Returns the sine of the X radian.
Tan (x) Returns the tangent of x radians.
Degrees (x) Convert radians to angles, such as degrees (MATH.PI/2), returns 90.0
Radians (x) Convert an angle to radians
Python Math Constants
Constants Description
Pi Mathematical constant Pi (pi, usually denoted by π)
E The mathematical constant e,e is the natural constant (natural constant).
Python escape character

Python uses a backslash (\) to escape characters when special characters are needed in characters. As the following table:

Escape Character Description
\ (at end of line) Line continuation character
\\ Backslash symbol
\‘ Single quotation marks
\" Double quotes
\a Bell
\b BACKSPACE (Backspace)
\e Escape
\000 Empty
\ n Line break
\v Portrait tab
\ t Horizontal tab
\ r Enter
\f Page change
\oyy Octal number, the character represented by YY, for example: \o12 for newline
\xyy Hexadecimal number, the character represented by YY, for example: \x0a for line break
\other Other characters are output in normal format
Python string operator

The following table instance variable a value is the string "Hello" and the B variable value is "Python":

td>%
operator description instance
+ string Connection A + B output Result: Hellopython
* repeating output string a*2 output: Hellohello
[] Get the character a[1] Output from the string by index   e
[:] truncate part of the string /td> a[1:4] output   ell
in member operator-returns TRUE if the string contains the given character H in a   output result 1
not in member operator-returns TRUE if the string does not contain the given character M not in a   output result 1
r/r Raw String-Raw string: all strings are used directly as literal meanings, and no special or non-printable characters are escaped. The original string has almost exactly the same syntax as a normal string, except that the first quotation mark of the string is preceded by the letter "R" (which can be case). print R ' \ n '  prints \ n and   print R ' \ n ' prints \ n
format string look at chapters
Python three-quote (triple quotes)

Three quotation marks in Python can be used to copy complex strings:

Python three quotes allow a string to span multiple lines, and the string can contain line breaks, tabs, and other special characters.

The syntax for a triple quotation mark is a pair of consecutive single or double quotes (usually paired).

With string combinations, special string escapes can be tedious.

Unicode string

Defining a Unicode string in Python is as simple as defining a normal string: (Can be labeled Chinese)

>>> u ' Hello world! ' U ' Hello world! '

The lowercase "u" before the quotation mark indicates that a Unicode string is created here. If you want to add a special character, you can use Python's Unicode-escape encoding. As shown in the following example:

>>> u ' Hello\u0020world! ' U ' Hello world! '

The replaced \u0020 ID indicates that a Unicode character (a blank space) with encoded values of 0x0020 is inserted at the given location.

Python string built-in functions

String methods are slowly added from python1.6 to 2.0-they are also added to Jython.

These methods implement most of the methods of the string module, as shown in the following table, which lists the currently supported methods for string literals, all of which contain support for Unicode, and some are even specifically for Unicode.

Method Description

String.capitalize ()

Capitalize the first character of a string

String.center (width)

Returns the center of the original string and fills the new string with a space of length width

String.count (str, beg=0, End=len (String))

Returns the number of occurrences of STR in a string, if beg or end specifies that the number of STR occurrences in the specified range is returned

String.decode (encoding= ' UTF-8 ', errors= ' strict ')

Decodes a string in the encoded format specified by encoding, if an error defaults to a ValueError exception unless errors specifies ' ignore ' or ' replace '

String.encode (encoding= ' UTF-8 ', errors= ' strict ')

Encodes a string in the encoding format specified by encoding, if an error defaults to a ValueError exception unless errors specifies ' ignore ' or ' replace '

String.endswith (obj, beg=0, End=len (String))

Checks whether the string ends with obj, or returns False if beg or end specifies whether to end with obj in the specified range, or True if it is.

String.expandtabs (tabsize=8)

Turns the tab symbol in string strings to a space, and the default number of spaces Tabsize is 8.

String.find (str, beg=0, End=len (String))

Detects if STR is contained in a string, and if beg and end specify a range, the check is contained within the specified range, and returns 1 if the index value is returned.

String.index (str, beg=0, End=len (String))

Just like the Find () method, only if STR does not report an exception in string.

String.isalnum ()

If the string has at least one character and all characters are letters or numbers, return

Return True, otherwise False

String.isalpha ()

Returns True if the string has at least one character and all characters are letters.

otherwise returns False

String.isdecimal ()

Returns True if the string contains only a decimal number, otherwise False.

String.isdigit ()

Returns True if the string contains only a number, otherwise False.

String.islower ()

Returns True if the string contains at least one case-sensitive character, and all of these (case-sensitive) characters are lowercase, otherwise False

String.isnumeric ()

Returns True if the string contains only numeric characters, otherwise False

String.isspace ()

Returns True if the string contains only spaces, otherwise False is returned.

String.istitle ()

Returns True if string is heading (see Title ()), otherwise False

String.isupper ()

Returns True if the string contains at least one case-sensitive character, and all of these (case-sensitive) characters are uppercase, otherwise False

String.Join (seq)

Merges (concatenates) merges all the elements in the SEQ (the string representation) into a new string as a string delimiter

String.ljust (width)

Returns the left alignment of an original string and fills the new string with the width of length with a space

String.Lower ()

Converts all uppercase characters in a string to lowercase.

String.lstrip ()

Truncate the left space of a string

String.maketrans (Intab, Outtab])

The Maketrans () method is used to create a conversion table of character mappings, for the simplest invocation of two parameters, the first argument is a string that represents the character that needs to be converted, and the second argument is the target of the string representation of the transformation.

Max (str)

Returns the largest letter in the string str .

Min (str)

Returns the smallest letter in the string str .

String.partition (str)

A bit like the combination of find () and split (), from the first position where Str appears, divide the string into a 3-element tuple (STRING_PRE_STR,STR,STRING_POST_STR), if string STR is not included in the STRING_PRE_STR = = string.

String.Replace (str1, str2, Num=string.count (STR1))

Replace the str1 in string with the str2, if NUM is specified, the replacement is no more than num times.

String.rfind (str, Beg=0,end=len (String))

Similar to the Find () function, it is just looking from the right.

String.rindex (str, Beg=0,end=len (String))

Similar to index (), but starting from the right.

String.rjust (width)

Returns the right alignment of the original string and fills the new string with the width of the length with a space

String.rpartition (str)

Similar to the partition () function, it is just looking from the right.

String.rstrip ()

Removes a space at the end of a string string.

String.Split (str= "", Num=string.count (str))

Slice string with a delimiter of STR, if NUM has a specified value, only the NUM substring is delimited

String.splitlines (Num=string.count (' \ n '))

Returns a list that contains rows as elements, separated by rows, and if num specifies that only num rows are sliced.

String.startswith (obj, Beg=0,end=len (string))

Checks whether the string starts with obj, returns True, or False. If beg and end specify a value, the check is within the specified range.

String.strip ([obj])

Execute Lstrip () and Rstrip () on string

String.swapcase ()

Flip the case in a string

String.title ()

A string that returns "header", meaning that all words start with uppercase and the remaining letters are lowercase (see istitle ())

String.translate (str, del= "")

Converts a string of characters according to the table given by STR, which contains 256 characters,

The characters to filter out are placed in the Del parameter

String.upper ()

Convert lowercase letters in string to uppercase

String.zfill (width)

Returns a string of length width, the original string is right-aligned, and the front padding is 0

String.isdecimal ()

The Isdecimal () method checks whether a string contains only decimal characters. This method exists only in Unicode objects.

Python Learning note Five: numbers and strings

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.