Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are Python numeric operations and strings?

2025-04-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly talks about "what are the numerical operations and strings of Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are Python numeric operations and strings?"

1. Operator

+, -, * and / like other languages, parentheses (()) are used for grouping

2. Int and float

Integers (for example, 2,4,20) are of type int, and numbers with decimal parts (for example, 5.0,1.6) are of type float.

3, /, /%

Division (/) always returns a floating point number. To return only integer results (drop any decimal parts), you can use the / / operator (floor division); to calculate the remainder, you can use%

> > 17 / 3 # classic division returns a float

5.666666666666667

> > >

> > 17 / / 3 # floor division discards the fractional part

five

> > 17 3 # the operator returns the remainder of the division

two

> 5 * 3 + 2 # result * divisor + remainder

seventeen

4. * * power

You can also use the * operator to calculate the power [1]:

> 5 * * 2 # 5 squared

twenty-five

> 2 * * 7 # 2 to the power of 7

one hundred and twenty eight

5. = assignment

The equal sign ('=') is used to assign values to variables. After the assignment, no results are displayed until the next prompt:

> width = 20

> height = 59.9

> width * height

nine hundred

Variables must be "defined" (assigned) before they are used, otherwise an error will occur:

> # try to access an undefined variable

... N

Traceback (most recent call last):

File "", line 1, in

NameError: name 'n'is not defined

6. in the mixed calculation of integers and floating-point numbers, integers are converted to floating-point numbers:

> > 3 * 3.75 / 1.5

7.5

> > 7.0 / 2

3.5

In interactive mode, the value of the most recent expression is assigned to the variable _. In this way, we can use it as a desktop calculator, which can be easily used for continuous computing, such as:

> tax = 12.5100

> price = 100.50

> price * tax

12.5625

> price + _

113.0625

> > round (_, 2)

113.06

This variable is read-only to the user. Don't try to assign it-you only create a separate local variable with the same name, which shields the magic effects of the system's built-in variables.

In addition to int and float,Python, other numeric types are supported, such as Decimal and Fraction. Python also has built-in support for plural, using the suffix j or J to represent imaginary parts (for example, 3x5j). II. String

1. Citation method: single or double quotation marks

Single quotation marks ('...') can be used in python Or double quotes (".") Identity string. Can be used to escape quotation marks:

> 'spam eggs' # single quotes

'spam eggs'

> > 'doesn't' # use' to escape the single quote...

"doesn't"

> "doesn't" #... or use double quotes instead

"doesn't"

>'"Yes," he said.'

'"Yes," he said.'

"" Yes, "he said."

'"Yes," he said.'

>'"Isn't," she said.'

'"Isn't," she said.'

In the interactive interpreter, the output string is enclosed in quotation marks and the special characters are escaped with a backslash. Although it may not look the same as the input, the two strings are equal.

2. RMurray-original string

If the character you precede is treated as a special character, you can use the original string by putting an r before the first quotation mark:

> print ('Crane somename') # here n means newline!

C:some

Ame

> print (ringing Corel somename') # note the r before the quote

C:somename

3. The text of the string is displayed in multiple lines.

One way is to use three quotation marks: "." Or...''. The newline character at the end of the line is automatically included in the string, but this behavior can be avoided by adding it to the end of the line. The following example: you can use a backslash as a continuous string at the end of a line, which indicates that the next line is logically subsequent to this line:

Print ("

Usage: thingy [OPTIONS]

-h Display this usage message

-H hostname Hostname to connect to

"")

The following output is generated (note that there is no first line at the beginning):

Usage: thingy [OPTIONS]

-h Display this usage message

-H hostname Hostname to connect to

4. Strings can be concatenated by the + operator (glued together) and can be repeated by *:

# 3 times' un', followed by 'ium'

> 3 * 'un' +' ium'

'unununium'

5. Two adjacent string texts are automatically concatenated together. :

> > 'Py'' thon'

'Python'

It is only used for two string literals, not for string expressions:

> prefix = 'Py'

> prefix 'thon' # can't concatenate a variable and a string literal

...

SyntaxError: invalid syntax

> ('un' * 3)' ium'

...

SyntaxError: invalid syntax

If you want to concatenate multiple variables or concatenate a variable with a string text, use +:

> > prefix + 'thon'

'Python'

This feature is especially useful when you want to split long strings:

> text = ('Put several strings within parentheses')

'to have them joined together.')

> text

'Put several strings within parentheses to have them joined together.'6, strings can also be intercepted (retrieved). Similar to C, the first character index of a string is 0.

Python does not have a separate character type; a character is a simple string of length 1. :

> word = 'Python'

> word [0] # character in position 0

'P'

> word [5] # character in position 5

'n'

The index can also be negative, which causes the calculation to start from the right. For example:

> word [- 1] # last character

'n'

> word [- 2] # second-last character

'o'

> word [- 6]

'P'

Note that-0 is actually 0, so it doesn't cause the calculation to start on the right.

In addition to indexing, slicing is also supported. The index is used to get a single character, and slicing gives you a substring:

> word [0:2] # characters from position 0 (included) to 2 (excluded)

'Py'

> word [2:5] # characters from position 2 (included) to 5 (excluded)

'tho'

Note that it contains the starting character, not the character at the end. This makes s [: I] + s [I:] always equal to s:

> word [: 2] + word [2:]

'Python'

> word [: 4] + word [4:]

'Python'

The index of the slice has a very useful default value; the omitted first index defaults to zero and the omitted second index defaults to the size of the sliced string. :

> word [: 2] # character from the beginning to position 2 (excluded)

'Py'

> word [4:] # characters from position 4 (included) to the end

'on'

> word [- 2:] # characters from the second-last (included) to the end

'on'

There is a way to easily remember how slicing works: the index when slicing is between two characters. The first character on the left has an index of 0, while a string of length n has an index of n on the right of the last character. For example:

+-+-

| | P | y | t | h | o | n |

+-+-

0 1 2 3 4 5 6

-6-5-4-3-2-1

The first line of numbers in the text gives the index point 0 in the string. six. The second line gives the corresponding negative index. Slices are all characters between the boundaries marked by two numeric values from I to j.

For a non-negative index, if the top and bottom are within the boundary, the slice length is the difference between the two indexes. For example, word [1:3] is 2.

Trying to use an index that is too large results in an error:

> word [42] # the word only has 6 characters

Traceback (most recent call last):

File "", line 1, in

IndexError: string index out of range

Python can gracefully handle meaningless slice indexes: an overly large index value (that is, a subscript value greater than the actual length of the string) will be replaced by the actual length of the string, and an empty string will be returned when the upper boundary is larger than the lower boundary (that is, the left value of the slice is greater than the right value):

> word [4:42]

'on'

> word [42:]

''

Python strings cannot be changed-they are immutable. Therefore, the position assigned to the string index results in an error:

> word [0] ='J'

...

TypeError: 'str' object does not support item assignment

> word [2:] = 'py'

...

TypeError: 'str' object does not support item assignment

If you need a different string, you should create a new one:

>'J' + word [1:]

'Jython'

> word [: 2] + 'py'

'Pypy'

The built-in function len () returns the string length:

> s = 'supercalifragilisticexpialidocious'

> > len (s)

At this point, I believe you have a deeper understanding of "Python numeric operations and strings". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report