Foundation of Python: number string and list

flydean 2021-02-23 01:38:18
foundation python number string list


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 !

版权声明
本文为[flydean]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210222192159324Q.html

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database