brief introduction

Python Its main application is scientific calculation , The foundation of scientific calculation is numbers , Strings and lists . This article will introduce the usage of these three data types in detail .

Numbers

Numbers are a very important type in any scientific calculation , stay Python The most common type of number in is int and float.

Look at a few basic number operations :

In [8]: 1+1
Out[8]: 2 In [9]: 3*2 + 10
Out[9]: 16 In [10]: (65 + 23) / 4
Out[10]: 22.0

We can see it up here , There are no decimals int type , With decimals is float type .

Division operations (/) Always return floating point type . If you want to do it floor division Get an integer result ( Ignore the decimal part ) You can use // Operator ; If you want to calculate the remainder , have access to %

In [11]: 54 / 4
Out[11]: 13.5 In [12]: 54 // 4
Out[12]: 13 In [13]: 54 % 4
Out[13]: 2

** It can be expressed as a power operation :

In [14]: 4 ** 3
Out[14]: 64

We can assign numbers to specific variables , And you can use this variable for subsequent operations .

In [15]: a = 12
In [16]: b = 14
In [17]: a * b
Out[17]: 168

In an interactive environment ,_ Represents the last output :

In [17]: a * b
Out[17]: 168 In [18]: 100 + _
Out[18]: 268

except int and float,Python Other data types are also supported , such as Decimal and Fraction, It even supports plural .

character string

Python There are three representations of strings in , You can use single quotes , Double quotation marks and triple quotation marks .

In [19]: site1 = 'www.flydean.com'
In [20]: site2= "www.flydean.com"
In [21]: site3= """www.flydean.com"""

Three quotes are mainly used for cross line output , Carriage returns in a string are automatically included in the string , If you don't want to include , Add a... At the end of the line \ that will do . as follows :

print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")

If you need to escape , You can use backslashes \

In [22]: site4 = "www.\"flydean\".com"
In [23]: site4
Out[23]: 'www."flydean".com'

If you don't want to go ahead \ The character of escape into a special character , have access to Original string The way , Add... Before quotation marks r that will do :

In [24]: print(r"www.\"flydean\".com")
www.\"flydean\".com

Strings are passed through + To connect , You can also use * To copy :

In [25]: "www" + "flydean.com"
Out[25]: 'wwwflydean.com' In [26]: "www.flydean.com" * 3
Out[26]: 'www.flydean.comwww.flydean.comwww.flydean.com'

Two or more adjacent string literal ( Quoted character ) Will automatically connect together .

In [27]: "www" "flydean.com"
Out[27]: 'wwwflydean.com'

Be careful , The auto connect operation above , It only works for two literal quantities , If it is a variable, an error will be reported .

Strings are treated as arrays of characters , So you can go through string[index] To visit in the form of .

In [28]: site5 = "www.flydean.com"
In [29]: site5[3]
Out[29]: '.'

If the index is negative , It's going to start counting from the right :

In [30]: site5[-3]
Out[30]: 'c'

because -0 and 0 It's the same , So negative numbers come from -1 At the beginning .

Except index , String also supports section . Index can get a single character , and section You can get substrings :

In [31]: site5[1:5]
Out[31]: 'ww.f'

Note that the beginning of the slice is always included in the result , And the end is not included . This makes s[:i] + s[i:] Always equal to s

In [33]: site5[:4]+site5[4:]
Out[33]: 'www.flydean.com'

The index of slices has a default value , The default value for omitting the start index is 0.

If the index exceeds the range of the string, an out of bounds error is sent .

In [34]: site5[100]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-34-fc1f475f725b> in <module>()
----> 1 site5[100] IndexError: string index out of range

however , The out of bounds index in the slice is automatically processed :

In [36]: site5[:100]
Out[36]: 'www.flydean.com'

Because strings are immutable , So we can't modify a string in the form of an index :

In [37]: site[2] = "A"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-37-9147d44bd80c> in <module>()
----> 1 site[2] = "A" TypeError: 'str' object does not support item assignment

len Used to count the length of a string :

In [38]: len(site5)
Out[38]: 15

String object str

The essence of string is string object str.

May have a look str Basic approach :

In [39]: site5.
capitalize() encode() format() isalpha() islower() istitle() lower() replace() rpartition() splitlines() title()
casefold() endswith() format_map() isdecimal() isnumeric() isupper() lstrip() rfind() rsplit() startswith() translate()
center() expandtabs() index() isdigit() isprintable() join() maketrans() rindex() rstrip() strip() upper()
count() find() isalnum() isidentifier() isspace() ljust() partition() rjust() split() swapcase() zfill()

Students who are interested can study it by themselves .

list

A list is a collection of data represented in square brackets . The data in the list can be of multiple data types , But in general , We use the same data type in a list .

In [40]: ages = [ 10, 14, 18, 20 ,25]
In [41]: ages
Out[41]: [10, 14, 18, 20, 25]

Just like a string , Lists also support indexing and slicing . in fact , As long as it is sequence Type of data type , Both support indexing and slicing .

In [42]: ages[3]
Out[42]: 20 In [43]: ages[:2]
Out[43]: [10, 14] In [44]: ages[:]
Out[44]: [10, 14, 18, 20, 25]

Be careful , A slice of the list returns a new list . But this new list is a shallow copy , It means that the elements in the new list are references to the elements in the original list .

The list also supports splicing operations :

In [45]: ages + [9, 11]
Out[45]: [10, 14, 18, 20, 25, 9, 11]

and String The immutability is different , The list is variable , This means that we can modify the value of the list through the index :

In [46]: ages[0] = 100
In [47]: ages
Out[47]: [100, 14, 18, 20, 25]

The underlying type of the list is list, We can look at it list The method in :

In [51]: ages.
append() count() insert() reverse()
clear() extend() pop() sort()
copy() index() remove()

We can use append To attach list Value , You can also use count To statistics list And so on .

We mentioned above , A slice of a list is a reference to the original list , So we can assign values to slices , To modify the values of the original list :

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

Lists can also be nested , Build multi tier lists :

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

This article has been included in http://www.flydean.com/03-python-number-list-string/

The most popular interpretation , The deepest dry goods , The most concise tutorial , There are so many tricks you don't know about waiting for you to discover !

Welcome to my official account. :「 Program those things 」, Know technology , Know you better !

Python The foundation : More articles on numeric strings and lists

  1. Python Basics data type ( character string 、 list 、 Dictionaries 、 Tuples 、 aggregate 、 Pile up 、 Stack 、 Trees )

    Data types have integers . Boolean . character string . list . Dictionaries . Tuples . aggregate . Pile up . Stacks and trees . 1. integer : Integers are numbers Digital representation python2 64 Bit machine , Range -2^63~2^63-1 Beyond the above scope ,python Automatically convert to l ...

  2. python Basic data types / character string / Tuples / list / Dictionaries

    Python data type Numeric type : int integer ,long Long integer ( stay python3.0 There's no distinction between integers and long integers ).float floating-point :complex The plural (python There is a decimal pool :-5--257): Boolean value ...

  3. python Basics 2 The string of 、 list 、 Dictionaries 、 aggregate

    Contents summary : One .python2 or 3 Two . String splicing 3、 ... and . character string Four . list . Yuan Zu 5、 ... and . Dictionaries 6、 ... and . aggregate 7、 ... and . practice One .python2 or python3 At present, most of them use python2.7, Over time ...

  4. Python The basic chapter : character string 、 The list of operations

    String manipulation Judge whether it is a number string = "200" string.isdigit() >>false To be improved .. The list of operations List is one of the most commonly used data types in the future , ...

  5. Python Basics ( Numbers , String method )

    Numbers : # Binary to decimal a=' v=int(a,base=2) print(v) Hexadecimal conversion # How many bits does the binary of the current number have at least b=2 v2=b.bit_length() print(v2) Numerical binary ...

  6. Chapter five :python The circular structure of the foundation and the list

    python The circular structure of the foundation and the list   python Basic compiler selection , Loop structure , list Content of this section python IDE The choice of Formatted output of string data type Loop structure list Simple shopping cart writing 1.pyth ...

  7. 『Python Basics -4』 character string

    # 『Python Basics -4』 character string Catalog 1. What is a string 2. Modify string 2.1 Modify the string size 2.2 Merge ( Splicing ) character string 2.3 Use the multiply sign '*' To achieve the superposition effect of strings . 2.4 Add null... To the string ...

  8. Python String of basic data type

    Python String of basic data type One .Python How to create a string stay python A string is formed by wrapping some text in quotation marks ( Quotation marks can be single quotation marks . Double quotes . Single three quotation marks , Double triple quotes , They are exactly the same ) >> ...

  9. python Basic numbers 、 character string 、 list 、 Tuples 、 Dictionaries

    Python Foundation two : 1. Operator : Judge whether something is contained in something : in   It's true not in   For false (1). Arithmetic operator : Operator describe example + Add   Represents the addition of two objects a + b Output results 3 ...

  10. Python Basic summary ( Strings are often used , Digital type conversion , Basic operators and process control )

    One . String common operations #Python strip() Method is used to remove the characters specified at the beginning and end of a string ( Default is space ) name='*egon**' print(name.strip('*'))# remove name Variables correspond to ...

Random recommendation

  1. UWP&amp;WP8.1 Redraw the picture WriteableBitmap usage Picture turn byte[] Array ,byte[] Array to picture

    --- Resume content start --- WriteableBitmap yes UWP and WP8.1 Drawing pictures , The most important way to reorganize pictures . The method is simple , Diversity of methods . By looking at the document ,WriteableBitmap The inheritance of is    ...

  2. Linux The performance parameters of the server

    Linux The performance parameters of the server One is based on Linux While the server of the operating system is running , It can also represent all kinds of parameter information . Generally speaking, operation and maintenance personnel . System administrators will be extremely sensitive to this data , But these parameters are also very important for developers , ...

  3. my ElasticSearch Summary of cluster deployment -- Big data search engine you have to know

    Abstract : There are three kinds of books in the world :1. Introduce knowledge ,2. Expound theory ,3. Reference book : There are also two kinds of knowledge :1. technology ,2. thought . Here's what I'm deploying ElasticSearch A summary of the experience in clustering , They fall roughly into the first category of knowledge “techknow ...

  4. [ turn ]Android Use Fragment The interface jumps down and returns one level at a time

      1. First, paste the project structure diagram : 2. First add an interface file BackHandledInterface.java, Define a setSelectedFragment Method is used to set the currently loaded Fragment At the top of the stack , Main boundary ...

  5. Reprint :javascript Drag sort , Simple example memo

    Reprinted from :http://blog.csdn.net/wang4978/article/details/6721157 <html> <head> <title> Drag the line ...

  6. Windbg Grab program crash dmp Method of file

    Windbg Grab program crash dmp Method of file One .        brief introduction windbg Is in windows Under the platform , Powerful user and kernel debugging tools . Compared with Visual Studio, It is a lightweight debugging tool , ...

  7. net Resume of software engineer

    Net Resume of software engineer surname      name : Wang Jingjing sex      other : Woman Date of birth : 1991-12 cadastral      Guan : hebei To live : Beijing learn      calendar : Specialty E-mail: 335659753@qq. ...

  8. LeetCode OJ 98. Validate Binary Search Tree

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  9. linux Scripts keep logs

    Use tee Make the screen and file output log . 2 >&1 in 2 It's error output ,1 It's standard output , 2>&1 It's standard and error output together . repo sync 2>&1 | tee -a ...

  10. sharepoint REST API Get folders and files

    Use REST Operation folder : Get folder url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Shared Documents')/f ...