python-string and list operation-day2

Source: Internet
Author: User

1. Data type 1.1 variable derivation data type

Variables: Used to record status
Variable value change is the change of state, the essence of program operation is to deal with a series of changes

1.2 Five basic data types:
    • Digital
    • String
    • List
    • Meta-group
    • Dictionary
1.2.1 Digital
    二进制:0101010     #对应的调用bin()    八进制:1-7         #对应的调用oct() 十六进制:0-9abcdef #对应的调用hex()
    • Integral type
    • Long integer type
    • Floating point
    • Boolean
    • Plural
1.2.2 Integral type

Built-in functions are: Int ()
Int (a,base=b)
A is a variable or "A (undefined variable)"
Base=b B tells the computer what the binary operation is
All objects
Age =---> int (TEN)--->init ---> Call
All of these variables are ultimately created by using objects to generate the
Int () in Python3 has no distinction between integral type and long integer type

1.2.3 Boolean
True 和 False1和0
1.2.4 Float Float

Python's floating-point numbers are decimals in math.

1.2.5 plural

The complex number consists of real and imaginary parts, the general form is X+yj, where x is the real part of the complex, and Y is the imaginary part of the complex, where x and y are real numbers.
Note that the letter J of the imaginary part can be case-sensitive,

1.3 + 2.5j = = 1.3 + 2.5J
True

1.3 string

The definition of a string:
msg= "Hello World"

1.3.1 String Module Method 1:
#首字母大写:Print (Msg.capitalize ())#按照字符串是20个 Center DisplayPrint (Msg.center (20,‘*‘))#字符串中包含所选字符的计数 mode = (' character ', start=1,end=2)Print (Msg.count (' L ',1,3)) which contains the selected character is determined by the start and end character positions#按照字符提取, [] The number in the [] string represents the character subscriptPrint (msg[4])#判断一个字符串是否是以 ' d ' End ofPrint (Msg.endswith (' d '))#指定空格的个数 expandtabs Just for the TAB key or the SPACEBAR msg1=' A\TB '#\tprint (MSG1) print ( Msg1.expandtabs (10))  #找到对应字符的索引  Print (Msg.find ( ' d '))  #没有找到就直接输出-1 print (Msg.find ( ' z ')) print ( Msg.find ( ' d ', 1,11)) print ( ' {0},{1} '.  Format ( ' name ',  ' age ') print ( Span class= "hljs-string" > ' {name} '. format (name =  "stone"))        
1.3.2 String Module Method 2:
index索引:查看指定字符的索引isalnum:  判断字符都是数字msg3=‘123a‘   isalpha:  字符都是字母isdecimal:  判断是否是十进制数字## isdigit(): ## 判断是否是整型数字isnumeric:  判断是不是数字  isidentifier:  判断字符串内是否包含关键字;islower():  判断字符串是否是小写 isspace():  判断字符串是否是空格istitle():   是否是标题 单词首字母必须是大写的 其他的字符不能是大写的,isupper():  是否都是大写lhust():   左对齐  print(msg.ljust(10,‘*‘))rjust(): 右对齐lower(): 将所有的大写转换成小写upper(): 将所有的小写转换成大写lstrip(): 左边去除空格rstrip(): 去除右边的空格maketrans(): 将字符串进行替换 替换的字符串需要跟等长yfill(): 从右侧填充 
1.3.3 Common operations for strings
    • Remove blank strip (): Remove whitespace
    • Split Split ()
    • Length Len ()
    • Index MSG[3]: Character index
    • Slice Msg[0:3]: string slice Msg[2:7:2]: by step
2. Operator 2.1 arithmetic operations

2.2 Comparison operations

2.3 Assignment Operations

2.4-bit arithmetic


Note: ~ Example: 6 Explanation: Multiply the binary number +1 by-1, i.e. ~x =-(X+1),-(101 + 1) = 110

A bitwise reversal can only be used in front of a number. So writing 3+~5 can get the result-3, it's wrong to write a.

2.5 Logical operations

and annotations:
在Python 中,and 和 or 执行布尔逻辑演算,如你所期待的一样,但是它们并不返回布尔值;而是,返回它们实际进行比较的值之一。  在布尔上下文中从左到右演算表达式的值,如果布尔上下文中的所有值都为真,那么 and 返回最后一个值。  如果布尔上下文中的某个值为假,则 and 返回第一个假值  
or annotations:
or 时,在布尔上下文中从左到右演算值,就像 and 一样。如果有一个值为真,or 立刻返回该值如果所有的值都为假,or 返回最后一个假值注意 or 在布尔上下文中会一直进行表达式演算直到找到第一个真值,然后就会忽略剩余的比较值
And-or used in combination:
结合了前面的两种语法,推理即可。为加强程序可读性,最好与括号连用,例如:(1 and ‘x‘) or ‘y‘
2.6 Member operations

2.7 Identity Operations

3. For loop write program the most taboo is to duplicate code!!!

Loop 10 times:

for i in range(10):    print(i)run执行输出:0 1 2 3 4 5 6 7 8 9 0 

If you do not want to start from 0:

in range(1,10):    print(i) run 执行结果:1 2 3 4 5 .. 9range(1,10):表示从1开始一直到9;range(2,7):表示从2开始一直到6;
3.1 Guessing Age Program:
#!/usr/bin/env pythonright_age = 60for i in  range(3): age = int(input("print you guess age:")) if age == right_age: print("guess right!") break elif age > right_age: print("guess smaller!") else: print("guess bigger!")else: #如果for循环正常结束,就执行下面的语句 print("too many times!!!") # == exit("too many attempts") 
3.2 For loop else syntax test:
for i  in range(10):    print(i)    if i == 5: print("5退出!") breakelse: print("循环正常退出!")执行结果
3.3 For loop-nested loops:
for i in range(10):    print(i)    for j in range(10): if j < 6: #break # 跳出当前层循环 continue #跳出当次循环,继续下一次循环 print(i,j)
3.4 While loop

Dead loop
Determine age and use while+ conditions to perform loops.

 #!/usr/bin/env pythonage= 56count = 0 # count while count<< Span class= "Hljs-number" > 3: # judge execution three times jump out of loop guess = input ( "guess Age: ") if guess.isdigit (): guess = Int (guess) else: continue if guess = = 56:print (" OK ") break elif guess > Age:print ( "bigger") else:print ( "smaller") count + = 1             
4. List 4.1 list function defines a list: names = [] or name = List (1,2,4) names = [] The final call is the List Class 4.1.1 Increase Appendnames.append ()
例子:names.append("zheng")  print(names)  names.insert(2,"app")在指定的index之前插入 
4.1.2 Delete del pop () remove () Three ways: Names.remove () Names.pop () del Names[index]
names.remove("app"):删除找到的第一个key  del names[3]:直接指定索引删除 names.pop(3):指定索引删除,不指定索引直接删除最后一个。 
4.1.3 Change
names[1] = "wang" 直接指定索引替换成想要的  print(names)
4.1.4 Search
print(name[-2])        #直接指定索引取出  print(name[0::2]) #按照步长取值 print(name[-3:]) #取最后三个元素 print(name[:3]) #取前三个元素 print(name.index("wang"))#取元素的下标 
4.1.5 Counts Count ()
print("count",names.count("wang"))# 获取  
4.1.6 Clear Clear ()
name.clear()            #清空列表  
4.1.7 extension Merge Extend ()
name.extend("liang")    #作用是两个列表的合并  name1=["hello","nihao"]  name2=["ca","haha"] name1.extend(name2) #列表扩展 name1 [‘hello‘, ‘nihao‘, ‘ca‘, ‘haha‘] 
4.1.8 sorting sort () Name.sort () #排序4.1.9 Inversion Reverse ()
name.reverse()          #反转  python3中列表中必须统一 元素中字符串与数字不能混用  
4.1.10 copy () Copy syntax to re-establish memory with original content memory ID storage location different 4.1.11 list length len ()
name = [11,22,33]print(len(name))3
4.3 Looping a list
for i in names:    print(i)enunerate(name):
4.4 List of Judgments
len(a)# 判断一个列表的长度val >=0 and val <len(a)
4.5 Data type conversion built-in functions summary

5 Python Grooming-Small 5.1 execute script incoming parameters

Python has a large number of modules, which makes developing Python programs very concise. The class library includes three:

Python内部提供的模块业内开源的模块程序员自己开发的模块

Python internally provides a SYS module where SYS.ARGV is used to capture parameters passed in when executing a python script

#!/usr/bin/env python# -*- coding: utf-8 -*- import sys print sys.argv  

 

5.2 Sys OS module small note

Python's strength is that he has a very rich and powerful standard library and third-party library, almost any function you want to implement has the corresponding Python library support, later in the course will be in depth to explain the various libraries commonly used, now, we first to symbolically learn 2 simple.

5.2.1 SYS Module
#!/usr/bin/env python# -*- coding: utf-8 -*-import sysprint(sys.argv)#输出$ python test.py helo world[‘test.py‘, ‘helo‘, ‘world‘] #把执行脚本时传递的参数获取到了
5.2.2 OS Module
os#!/usr/bin/env python# -*- coding: utf-8 -*- import os os.system("df -h") #调用系统命令
5.2.3 a complete combination.
os,sys os.system(‘‘.join(sys.argv[1:])) #把用户的输入的参数当作一条命令交给os.system来执行

python-string and list operation-day2

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.