Python 基礎知識

#數據結構python

##1.字符串
###首字母大寫方法 name="adb test" print(name.title())
###所有大寫 print(name.upper())
###所有小寫 print(name.lower())
###字符串合併 first="adb" sencond="test" print(first+" "+second)
###製表符和換行符,在字符串中添加\n\t就能夠
print("\n\tpython")
print("\n\t"+name)
###字符串刪除空白(包括\t,\n,空格),使用lstrip,rstrip,strip函數
lstrip 刪除字符串左側空白
rstrip 刪除字符串右側空白
strip 刪除字符串左右兩邊的空白

str1=" python"
str2="python "
str3=" python "
printf(str1.lstrip())
printf(str2.rstrip())
printf(str.strip())數據結構

##2.基本數據類型
##List []
array = ['aaa','bbb','ccc']
###添加插入元素
array.append("Item") 經過append追加元素
array.insert(0,"Item") insert插入元素
###刪除元素
del array[0] del刪除元素
array.remove['aaa'] 刪除指定的元素
numitem = array.pop() 彈出最後一個元素並返回
###元素排序
cars = ["bmw","audi","toyota","subaru"]
cars.sort() 排序,修改了cars的順序
print (cars)
cars.sort(reverse=True) 倒序
print (cars)
sorted(cars) 臨時排序, sorted方法返回一個臨時排序的list.
sorted(cars,reverse=True) 倒序
>>> print(sorted(cars,reverse=True))
['toyota', 'subaru', 'bmw', 'audi']
###反轉列表
cars.reverse()
>>> print cars
['subaru', 'toyota', 'audi', 'bmw']
###列表長度
len(cars)
4
###遍歷列表
>>> for item in cars:
... print(item)
subaru
toyota
audi
bmw app

###數值列表
range是左開右閉的原則 函數

>>> for i in range(1,5):
... print i
1
2
3
4 排序

range返回的就是一個list,所以能夠用來構造list.
>>> print range(1,6)
[1, 2, 3, 4, 5] ip

range的第三個參數表示步長.
>>> numbers = list(range(0,11,2))
>>> print numbers
[0, 2, 4, 6, 8, 10] rem

min,max, sum統計數據
>>> print numbers
[0, 3, 6, 9]
>>> print min(numbers)
0
>>> print max(numbers)
9
>>> print sum(numbers)
18字符串

###列表解析
>>> squares = [ value**2 for value in range(1,11)]  
>>> print squares  
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] it

相關文章
相關標籤/搜索