1. 程式人生 > 實用技巧 >Day 6 基本資料型別常用操作及內建方法

Day 6 基本資料型別常用操作及內建方法

一 for 迴圈知識補充

range 範圍

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Notice that the ending number is not included.

We can omit the starting position and step parameters.

可以省略起始位置和步長,預設起始位置為0,步長為1

and the step could be negative 步長可以為負數

#range步長的用法
for i in range(1, 10, 2):
print(i)
#range步長為負
for i in range(20, 10, -2):
print(i)

enumerate 列舉索引

Python's enumerate() lets you write Pythonic for loops when you need a count and the value from an iterable(可迭代的). The big advantage of enumerate() is that it returns a tuple(元組) with the counter and value, so you don't have to increment the counter yourself.

for hobby in enumerate(["chi", "he", "piao", "du"]): #基本用法
print(hobby)

#也可以在for後面跟2個變數
for num, hobby in enumerate(["chi", "he", "piao", "du"]):
print(num, hobby)
print(type(num)) #輸出的第一個變數為整型
print(num+1, hobby)

二 可變型別與不可變型別

mutable object and immutable object

Every variable in python holds an instance of an object. There are two types of objects in python:mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime and it can’t be changed afterwards. However, it’s state can be changed if it is a mutable object.

To summarise the difference, mutable objects can change their state or contents and immutable objects can’t change their state or content.

Mutable typeImmutable type
list int,float,complex
dictionary string
tuple

三 數字型別 numeric types

Variables of numeric types are created when you assign a value to them:

Numeric types usually used for arithmetic and comparison calculation

they are all immutable types

一般為不可變型別

定義 definition

Int

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Float

Float, or "floating point number" is a number, positive or negative, containing one or more decimals.

Complex

Complex numbers are written with a "j" as the imaginary part.

a = 5 + 3j
print(type(a))
print(a.real) # 列印複數實部
print(a.imag) # 列印複數虛部

轉換 Convert

These types can be converted to each other

And we can turn "string" into "Int" and “float”

But the string here must consist of numbers

a = -2  # 整型轉換為浮點型,注意後面要有.0
b = float(a)
print(b, type(b))

c = -1.987 # 浮點型轉換為整型,注意是直接擷取,不是四捨五入也不是取整
d = int(c)
print(d, type(d))

e = "1997" # 字串轉換為整型或浮點型
f = int(e)
g = float(e)
print(f, type(f), g, type(g))

四 字串 Strings

定義 definition

Strings in python are surrounded by either single quotation marks, or double quotation marks.

在一對單引號或者雙引號之間,或者三引號之間(用於多行內容)

Strings are immutable types

轉換 Convert

All types can be converted to strings by command str()

五 字串操作

轉義符 Escape Characters "\"

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by double quotes:

We can also put r in front of the string to achieve that when there is an escape character in the string

txt = "We are the so-called \"Vikings\" from the north."
txt = "We are the so-called 'Vikings' from the north."
print(r"a/b/c")

字串可以使用索引 Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Square brackets(中括號) can be used to access elements of the string.

my_name="matthews"
print(my_name[4]) #注意,索引從0開始數

迴圈取用字串 Looping through a string

Since strings are arrays, we can loop through the characters in a string, with a for loop.

my_name="matthews"
for i in my_name:
print(i)

切片 Slicing

You can return a range of characters by using the slice syntax(句法).

Specify(指定) the start index and the end index, separated by a colon(冒號), to return a part of the string.

my_name = "matthews"
print(my_name[2:5]) # 注意,不包括終止值
print(my_name[1:4:2]) # 使用步數
print(my_name[4:1:-1]) # 注意,使用步數完成倒序,方法,顛倒前後兩數,並全部-1
print(my_name[:]) # 注意,相當於複製操作

成員運算 in/ not in

To check if a certain phrase or character is present in a string, we can use the keyword in:

my_name = "matthews"
if "at" in my_name:
print ("Yes,'at' is present")

移除前後空格 Strip (Remove whitespace)

Whitespace is the space before and/or after the actual text, and very often you want to remove this space.

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

替換 Replace String

The replace() method replaces a string with another string:

my_name = "matthews t"
print(my_name.replace("t","b")) #把所有的t替換為b
print(my_name.replace("tt","b")) #把所有的tt替換為b

切分 Split String

The split() method returns a list where the text between the specified separator becomes the list items.

ip_address="192.168.1.1"
print(ip_address.split("."))

字串中的引用 Format String

We cannot combine strings and numbers directly

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:

基本用法

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

按順序引用

The format() method takes unlimited number of arguments, and are placed into the respective placeholders

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

按索引引用

You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

六 字串完整內建函式

https://www.runoob.com/python3/python3-string.html

七 列表

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

定義 Definition

Lists are created using square brackets:

列表元素特點 List Items

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

有序的 Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.

可變的 Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.

允許重複 Allow Duplicates

Since lists are indexed, lists can have items with the same value:

更改列表元素 Change list items

取列表元素 Access List Items

List items are indexed and you can access them by referring to the index number:

更改列表元素 Change List Items

To change the value of a specific item, refer to the index number

To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

增加列表元素 Add list items

Append items 末位增加一個元素

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

Insert items 指定位置增加一個元素

thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

Extend list 指定位置增加多個元素

thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

Add Any Iterable 可以增加任意型別的可迭代物件

thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

Remove List Items 刪除列表元素

Remove Specified Item 刪除指定元素

The remove() method removes the specified item

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

Remove Specified Index 刪除指定索引元素

The pop() method removes the specified index.

thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)

Clear the List 清空列表

The clear() method empties the list.

The list still remains, but it has no content.

thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)