Python notes (i)

Source: Internet
Author: User

String processing
Single and double quotes
. Title (): Capitalize the first letter of each word and the rest of the lower case (regardless of the original)
. Upper (): Capitalize all letters in a string
. Lower (): Change all letters in a string to lowercase
. Strip (): Delete white space (spaces and tabs) at the beginning and end of the line (direct input variable return value to see otherwise no effect)
. Lstrip (): Delete left, which is the beginning of the line
. Rstrip (): Delete the friend side, the end of the
Combine strings directly with a plus sign: +
Escaped (regardless of single double quote):
\ t: Tab
\ n: Line break

字符串反转:    a="abcdef"    a[::-1]:“fedcba”

Variable type conversions
Integer or other---string: str (variable)

Comments
#: Single line comment
"" "" ": Multiline Comment

List
Assignment: var=["AA", "BB" can first create empty list
Return last: Var[-1]
At the end add:. Append ("AAA")
Add at any location:. Insert (index position, "CCC")
Delete: Del var[index position] (the index behind it will replace the deleted index)
. Remove (value): Delete by value, stop only once, and if you delete multiple identical values you need to use loops to determine whether to delete the last element in the clean
Pop-up list:. Pop () (pop-up elements can be used, but not present in the list)
Delete and eject differences: Not available after deletion, pop-up can use this popup element

排序:    .sort():对列表永久性排序(按照首字母)        反向排序,传递参数:.sort(reverse=True)     sorted(列表):临时排序,返回排序好的列表,但是对原来的列表无影响        临时反向排序:sorted(列表,reverse=True)倒着打印列表:.reverse()    反转列表:reverse(列表)获取列表长度:len(列表)遍历列表:for i in 列表:    最好的命名方式,列表取复数,遍历变量取单数,即:        for cat in cats:创建数字列表:    range():生成一串数字         range(1,6):生成1到5(没有6)         range(2,11,2):跳着生成    在生成一串数字之后,使用list()将其转换成列表:         list(range(1,6))    上面的可以简写为一行:squares = [value**2 for value in range(1,11)] 找极值:    min(digits):最小值    max(digits):最大值    sum(digits):求和列表切片:    列表[1:4] :打印从1开始到4的前边3    列表[:4] :如果不写起始则从头开始    列表[1:] :如果不写结束则一直到末尾    列表[-5:] :打印出最后5个元素列表切片可用于遍历一部分列表复制列表:    列表2=列表1[:](可以指定复制的范围)        后头必须有方括号,否则是两个名字指向同一个列表,不是复制

Tuples: Non-modifiable lists (using the same list)
tuple = (200,50)
print (tuple [0])

不能单独修改一个元素的值,但是可以整体赋值:    

Programming Standards:
Indent to four spaces
Maximum of 80 characters in a row
Empty line don't abuse

If statement
If VAR1=VAR2:
COMMAND
Else
COMMAND

or write:
VAR1 = = VAR2

在判断时区分大小写,如果VAR1位大写,VAR2为小写,则if返回值为FALSE    如果不想区分大小写,可以先使用“.lower()”都转换为小写再比,而且不会影响原来变量中的内容比较符号:    等于:==    不等于:!=    大\小(等)于:>、<、<=、>=    条件与:and(and两边要有空格,和变量分开)(and两边的潘丹条件可使用小括号包裹起来)    条件或:or    判断一个特定的值是否在列表中:in        ‘value‘ in lists        不包含 not in    布尔值:True、False(大小写固定,必须首字母大写)

If format: (Elif and Else sections can be omitted)
If age < 4:
Print ("Your admission cost is $.")
Elif Age < 18:
Print ("Your admission cost is $.")
Else
Print ("Your admission cost is $.")

Working with instances: (judging whether in the list)
requested_toppings = [' mushrooms ', ' extra cheese ']
If ' mushrooms ' in requested_toppings:
Print ("Adding mushrooms.")
If ' pepperoni ' in requested_toppings:
Print ("Adding pepperoni.")
If ' extra cheese ' in requested_toppings:
Print ("Adding extra cheese.")

If lists: (Determines whether the list is empty)

Dictionaries (no order, only concerned with correlation of key-value pairs)
Assignment value:
Alien_0 = {} (create empty dictionary)
Alien_0 = {' Color ': ' green ', ' Points ': 5} (Bulk Assignment)
alien_0[' x_position '] = 0 (discrete assignment)
Use:
Print (alien_0[' color ')) (single printing)
Print (ALIEN_0) (all printed)

Delete: Del alien_0[' points '] traversal dictionary: user_0 = {' username ': ' efermi ', ' first ': ' Enrico ', ' Last ': ' Fermi ',} for key, value in User_0.items (): (using the items function to traverse a key-value pair) (if the items function is not used, and only one variable is output index) for I in Lists.keys (): (traversal index) for I in Lists.values (): (traversal value) (key and value these two words can be arbitrarily UP) The dictionary is unordered, sort it: for name in sorted (Favorite_languages.keys ()): Reject duplicates: For language in Set (Favorite_lang Uages.values ()): Dictionary nesting: Storing a series of dictionaries in a list, or storing a list as a value in a dictionary, which is called nesting. You can nest dictionaries in lists, nest lists in dictionaries, or even nest dictionaries in dictionaries alien_0 = {' Color ': ' green ', ' Points ': 5} alien_1 = {' Color ': ' Yellow ', ' poin TS ': ten} alien_2 = {' Color ': ' Red ', ' Points ':} aliens = [Alien_0, alien_1, alien_2] for alien in a Liens:print (Alien) Output: {' color ': ' green ', ' Points ': 5} {' Color ': ' Yellow ', ' points ': 1 0} {' Color ': ' Red ', ' points ': 15} Dynamically created dictionary saved in list: Aliens =[]    ? For Alien_number in range (30):? New_alien = {' Color ': ' green ', ' points ': 5, ' speed ': ' Slow '}?                                 Aliens.append (New_alien) can then modify the list of contents in the dictionary by traversing the list to save in the dictionary: favorite_languages = { ' Jen ': [' python ', ' Ruby '], ' Sarah ': [' C '], '            Edward ': [' Ruby ', ' Go ', ' Phil ': [' python ', ' Haskell '],} For name, languages in Favorite_languages.items (): Print ("\ n" + name.title () + "s favorite lang         Uages is: ") for language in languages: (Loop included) print (" \ T "+ language.title ()) Dictionary Save Dictionary: (preferably each sub-dictionary contains the same values, so easy to manage) users = {' Aeinstein ': {' first ': ' Albert                             ', ' last ': ' Einstein ', ' Location ': ' Princeton ', }, ' MCUrie ': {' first ': ' Marie ', ' last ': ' Curie ', ' Location ': ' Paris ',},}

Input:
Var_str=input ("Write some Hints Here") (This is Python3, use raw_input in Python2)
Sometimes the hint is that more than one line of information can be stored using a variable (\ n is a newline)
Var_int=int (VAR_STR) (Convert string type to Integer)

while循环:    while 判断条件:(可以是True或False(首字母大写))        continue        break    while和列表搭配:        while lists:(当列表空时结束)            lists.pop()(使用pop函数输出,或者使用remove,不然死循环)                pop:弹出列表中最后一个元素                remove:删除列表中的值,但只删第一个,后头再有重复的不管,当想要删除列表中多个重复的值时,使用while来进行删除                    while ‘cat‘ in pets:                        

Python notes (i)

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.