Python number type int float and common operation methods

"Division"print(10/4)print(type(10/4))"rounding"print(10 // 4)print(type(10 // 4))"The result is a floating point"print(10) // 4.0)import math"round left"a = math.floor(-3.4)print(a)print(type(a))"truncated"a = math.trunc(-3.4)print(a)print( type(a))"round, round (global function)"a = round(-3.4)print(a)print(type(a))

Python string types and common operation methods

@\ Escape character @\n line feed @\b backspace@\t tab path = r'C:\abc\xyz.txt' # r plays the original role and eliminates the escape print(path)print(type(path) )print(len(path)) # Character length a ='ok'print(path + a) # Character addition print(a * 5) # Character repetition and superposition s ='abcdefghijklmn'print(s[0:4]) # Characters 1st to 5-1=4 print(s[-1]) # Output the last print(s[len(s)-1]) # Output the last print(s[:]) # Output all print(s[0:4:2]) # output the first and third print(int('42') + 1) # output as 43inta = ord('c') # ASCII code print(a)print(chr (99)) # Common methods of ASCII code : h ='hello'h = h.replace('e','a') # Replace
url ='abc'print(url.upper()) # Change to uppercase"character string display format description"a = '3+2={0}'.format(5)a = '3+2={0 }'.format(20)print(a)print(type(a))a = 3.3333333a ='{0:.2f}'.format(a) # The result is 3.33d = ('name':'Tom' ,'age': 10,'job':'dev')a ='Name: {0}, age: {1}'.format(d.get('name'), d.get('age') )# The result is name: Tom, age: 10
xx ='{}=>{}'.format(a, b)print(xx) # The result is a=>bprint('{name}=>{salary}'.format(name='Tom', salary= 9000)) # The result is Tom=>9000url ='uke.cc' print(url.startswith('u')) # The result of string discrimination is bool type print(url.endswith('kk')) print(url .find('.')) # Find method, location Python list type and common operation method
a = [1, 2, 3]b = [4, 5, 6]print(a + b) # The result is [1 2 3 4 5 6]ls = list('youxiude')print(ls)print(' o'in ls) # Determine whether o is a letter in youxiude li = [c * 3 for c in'code'] # for loop print(li)a = [1, 2, 3]a[1:2] = [4, 5] # The result is [1 4 5 3]print(a)print(a * 3) # The result is [1 4 5 3 1 4 5 3 1 4 5 3]
Common methods of operation:
a.append(7) # Append an element print(a)a.extend([7, 8, 9]) # Append a list print(a)a.sort() # Ascending order print(a)a.reverse() # Descending order print(a)a.pop() # Pop up (delete) the last print(a)"delete"del (a[0])print(a)b = a.index(4) # Find the position by index print( b)b = a.count(7) # counter print(b)a = [1, 2, 3]print(a)b = a.copy() # copy the elements in the list to bprint(b)
s ='classroom.com' ls = list(s) print(ls) ls[-1] ='n' print(ls) s =''.join(ls) # The connection character function output is classroom.conprint(s ) s ='|'.join(ls) # The connection character output is c|l|a|s|s|r|o|o|m|.|c|o|nprint(s) url ='abc. com,uke.com,dfg.cn' print(url.split(',')) # The string is cut into lists at intervals of Boolean type:"Compare, return Boolean type!="score = 60.3print(score> = 60) # The result is True
print(3 + True) # bool type is essentially intprint(3 + False) dictionary table type:
d = {'name':'Tom','age': 10,'job':'dev'}ex = d['age']print(ex) # The result is 10ex = d.get('name', 'Not found')print(ex) # The result is Tomex = d.get('ff','Not found')print(ex) # The result is not found

Tuple type:

t = (1, 2, 3, 4) # t = [1, 2, 3, 4] is a list, the difference: the list supports in-situ modification 
  • like
  • collect
  • share
    • Article report
GSmate published 2 original articles · won praise 0 · visits 56 private messages follow

Python numbers, strings, list types and common operations Related posts

  1. Python-5-digit random number generator, no repeated numbers

    I should print a random 5-digit number without repeated digits, and then ask the user for three digits. If the user’s number contains three digits for the random number, print"correct".I am using this code as a random numbernum = random.randint (0,99999)print (num)The problem is that it won't always ...

  2. python-rst2pdf: Quote automatically numbered numbers

    There are instructions in my first document with numbers inserted; and I use rst2pdf: counter: instructions to automatically number them... figure:: Graphics\Manual_test_timeline.png :scale: 100% :align: center Figure :counter:`figure`. Manual Testing TimelineThe title is shown in Figure 1. Manually ...

  3. LeetCode-1021 Remove Outermost Parentheses Solution(with Java)

    1. Description:Notes:2. Examples:3.Solutions: 1 /** 2 * Created by sheepcore on 2018-12-24 3 */ 4 class Solution { 5 public String removeOuterParentheses(String S) { 6 StringBuilder s = new StringBuilder(); 7 int opened = 0; 8 for (char c : S.toCharArray()) { 9 if (c == '(' && opened++ > ...

  4. 08-Note: Python3 Number (Number)

    Python numeric data type is used to store numeric 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 reallocated. Use the del statement to delete references to some digital objects del vardel var_a, var_b Python supports th ...

  5. [Number Summary/Math Number Function] from python

    NumberIn the python documentation, several points to note:The Math module does not support functions of complex numbers, and functions of complex numbers are calculated using cmath. Therefore, most of them do not support plurals.Under the math module, unless the label is displayed, it returns a floa ...

  6. Python Number(digit)

    The Python Number data type is used to store numeric values. The data type is not allowed to change, which means that if the value of the Number data type is changed, the memory space will be reallocated. The following example will create a Number object when the variable is assigned:A1 = 1 A2 = 10U ...

  7. Python3Number (Number)

    1. Mathematical functions2. Random number function3. Trigonometric functions4. Mathematical constants ...

  8. applet handles rich text path

    changefwb(strin){//Lazy loading process replaces src with v-lazy= let newStr= strin.replace(new RegExp(/src=\"/g), `mode="widthFix"src="${this. baseStatic}`);//v-lazy= },//Pass in the rich text and then automatically replace this.baseStatic is the prefix of the domain name //Use the src in the rich text of the scene without adding the domain name prefix, replace it with regular ...

  9. python - generate a random number len(10) containing 0-1s numbers

    The question is self-explanatory.I tried this.import randomnumber ="".join([str(random.randint(0,1)) for i in xrange(0,10)])print numberIs there a built-in function for the same?Solution:use:''.join(random.choice('01') for _ in xrange(10))This avoids int->str, or otherwise using a randrange in th ...

  10. Number Sorting Columns Containing Numbers and Strings (pandas/python)

    I have to sort a dataframe on column 1 and 2; column 1 contains numbers and text and should be sorted numerically first. In excel this is the standard way of sorting, but not in pandas.. I'm in pandas Details on how to do this can't be found in the manual.So this dataframe:Z 762320 297 01 865545 202 ...

  11. Number functions and random number functions in python

    1. Number function: import package math   1. abs(x): return the absolute value of the number (for the absolute value of integers). fabs(x) is a claim against floating-point numbers.   2. ceil(x) is rounded up, such as math.ceil(4.1) returns 5. floor(x) returns the rounded integer ...

  12. Japanese number to Arabic number converter in Python

    Is there an open source library in Python that can convert/translate Chinese characters to Arabic numerals?Input: 1,029,000,000 Output: 1,029,000,000Input: 167,172,600 Output: 167,172,600Input: 3,139 million Output: 3,139,000,000Japanese Numeric System: http://en.wikipedia.org/wiki/Japanese_numerals ...

  13. prime number judgment python

    China Mobile written test programming questions1. Prime number judgmentTitle description:For the expression n^2+n+41, when n takes an integer value in the range of [x,y], such as (-39<=x ...

  14. Blue Bridge special number (daffodil number) Python

    for b in range(1,9): for s in range(0,9): for g in range(0,9): if g**3+s**3+b**3==g+s *10+b*100: print(g+s*10+b*100)likecollectshareArticle reportmeini32 published 14 original articles · won praise 0 · visits 125 private messages follow ...

  15. Python Number (number) Ⅰ

    Python NumberThe Python Number data type http://www.xuanhe.net/ is used to store numeric values.The data type is not allowed to change, which means that if the value of the Number data type is changed, the memory space will be reallocated.The following example will create a Number object when the va ...

  16. python (enter the number and guess the number three times)

    Give the user three chances to guess. If the guess is correct within three times, it will show that the guess is correct and exit the loop. If the guess is not correct within three times, it will automatically exit the loop and display'Too stupid you...'. The user logs in (three chances of inputting ...

Recent Posts

  1. stl source code analysis-iterator concept and traits programming techniques

      The central idea of STL is to separate the data container and the algorithm, design them independently of each other, and finally put them together with a glue. This post glue is the iterator to be introduced next. Algorithms operate on containers through iterators.Iterator is a kind of ...

  2. BlackBerry-Use GPS and Google Maps to evaluate the port of Android applications

    Suppose I have an Android application that uses Google Maps and GPS. Use custom views and timers. How long does it take to develop it for Blackberry? What changes need to be made? Can the UI be reused? Although I know Java, I am still brand new to Blackberry. Please help me e...

  3. javascript-How to trigger "yellow tips" in Google Chrome or Chromium?

    Sometimes when using Chrome to browse the website, you can see the yellow prompt display. How to trigger the prompt of my own website?For example, if you try to go to The Independent's website, the system will prompt"The Independent now has a Google Chrome extension. Get the latest news about your f...

  4. (#3)The application cannot make this API call. JavaScript SDK

    I want to try a post using the JavaScript API, like this (id is the post ID):FB.api('/'+id+'/likes','post');For example, FB.api('/55353596297_10150952824706298/likes','post');It returns"(#3) The application cannot make this API call".Solution:Make sure you have the permissions that affect this permi...

  5. Python learning six days after class practice case (mainly aimed at the definition and use of python functions)

    Python learning 6th day after class practice case2019.07.19 1. Define a function that can input a message internally. If the message cannot be converted to a positive integer, re-enter it until it can be converted to a positive integer, and then return the converted positive integer to the out...

  6. Data structure and algorithm study notes (3) Sort search

    Centrally summarize common sorting algorithms (bubble sort, selection sort, insertion sort, Hill sort, merge sort, quick sort, heap sort, count sort, bucket sort) and search algorithms (sequential search, binary search, interpolation search, jump Search, fast search, hash search) algorithm principle...

  7. Python study notes (using Baidu AI for object recognition)

    Code part:Recognition effect:Code:# -*- coding: UTF-8 -*- import cv2 from aip import AipImageClassify def get_image(): cap = cv2.VideoCapture(0) while(1): # get a frame ret, frame = cap.read() # show a frame cv2.imshow("capture", frame) if cv2.waitKey(1) & 0xFF == ord('q'): cv2.imwrite("test.jpg...

  8. javascript-How to solve the "no way to push" error?

    Use the following code$.getJSON('services/getCharts.php', function(json) { var $line1 = []; $.each(json.posts, function() { $line1 = $line1.push([this.post.rectime,this.post.actual_value]); }); ... });Using JQuery gives me the following error:Uncaught TypeError: Object 1 has no method'push'Can anyon...

  9. Python genetic and evolutionary algorithm framework (1) Quick start with Geatpy.

    Original: http://blog.gqylpy.com/gqy/486Top: Martial arts cheats from a post-75s programmer-must-read (recommended by bloggers)Here, first submit the link to the martial arts cheats: http://blog.gqylpy.com/gqy/401/Hello, I am a geek! An old engineer born after 75!I will spend two minutes expressing ...

  10. Check if the file is on the network drive in python

    How to determine if the file is on a network drive? I want to include the path that looks like it is on a local disk, but a directory in the path is actually a symbolic link to a network drive.Solution:I assume you can get a list of network file systems and their basic mount points, you can get thes...