Python chapter 2&3 learning notes

方法是Python對數據執行的操作。

For example,

Upper() 全部大寫

Lower() 全部小寫

Title() 首字母大寫

rstrip() 刪除多餘空格(此時的刪除都是暫時的,非永久。如需永久需要重新幅值給原變量)

當在字符串中需要使用數字的時候,應在該數字的變量名前使用str()以避免錯誤

For example,

If you want output this sentence "I am 22 years old."

And your code will be

a=22# assumption

print("I am " + str(a) + "years old.")#Either "" or '' is ok.

There are the correct codes.

 

About Python List

Some skills:

1.      if you want to output the last element in the list, you can use this code:

list[-1]#in this place, list means the name of this list

Similarly, if you want to input the second to last number, you can use:

list[-2]

2.      some methods to modify, add or delete elements.

·        modify the element:

sights[0]='Beijing' means change the first element in the list sights to Beijing.

·        add element:

sights.append('Beijing') means add Beijing to the last of the list sights, sights.

insert(1, 'Beijing') means add Beijing to the place between the first element and the third element.

·        delete element:

del sights[0] means delete the first element  from the list.

poped_sight=sights.pop() means we can still use it when we delete the last element.

One thing to be noted, if we use poped_sight=sights.pop(1), it means that we still use the second element when we delete it.

sights.remove('Beijing') means delete the Beijing from the list. (If there are many Beijing in the list, this method only can delete the first Beijing.)

3.      Sort:

·        sort & alphabetically forever: use sort()

For example, sight.sort().

If we use sight.sort(reverse =True), it means reverse order.

·        temporary sort: use sorted() function.

For example, print(sorted(sights)).We can also use sorted(sights, reverse = True) to reverse order.

·        reverse order print: sights.reverse()

·        How to know the length of the list? The answer is use len() function.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章