day9 函式作業

2021-10-18 16:35:05 字數 3481 閱讀 4393

編寫乙個函式,交換指定字典的key和value。

# 例如:dict1=  -->  dict1=   

dict1=

defexchange

(dict1)

:"""

交換指定字典的key和value

:param dict1: 字典

:return: 字典

"""result =

dict

(zip

(dict1.values(

), dict1.keys())

)return result

print

(exchange(dict1)

)

編寫乙個函式,提取指定字串中所有的字母,然後拼接在一起產生乙個新的字串

# 例如: 傳入'12a&bc12d-+'   -->  'abcd'  

defget_str

(s):

""" 提取指定字串中的所有字母

:param s: 字串

:return: 返回只有字母的字串

"""new_s =

''for x in s:

if'a'

<= x <=

'z'or

'a'<= x <=

'z':

new_s += x

return new_s

寫乙個自己的capitalize函式,能夠將指定字串的首字母變成大寫字母

#例如: 'abc' -> 'abc'   '12asd'  --> '12asd'

defcapitalize1

(str1='')

:

寫乙個自己的endswith函式,判斷乙個字串是否已指定的字串結束

# 例如: 字串1:'abc231ab' 字串2:'ab' 函式結果為: true

# 字串1:'abc231ab' 字串2:'ab1' 函式結果為: false

defendswith1

(str1=

'', str2='')

: n =

len(str2)

if str2 == str1[

-n:]

:return

true

else

:return

false

print

(endswith1(

'abc231ab'

,'ab'

))

寫乙個自己的isdigit函式,判斷乙個字串是否是純數字字串

# 例如: '1234921'  結果: true

# '23函式' 結果: false

# 'a2390' 結果: false

defisdigit1

(str1='')

:for x in str1:

ifnot

'0'<= x <=

'9':

return

false

else

:return

true

寫乙個自己的upper函式,將乙個字串中所有的小寫字母變成大寫字母

# 例如: 'abh23好rp1'   結果: 'abh23好rp1'   

defnew_upper

(letter)

:

寫乙個自己的rjust函式,建立乙個字串的長度是指定長度,原字串在新字串中右對齊,剩下的部分用指定的字元填充

# 例如: 原字元:'abc'  寬度: 7  字元:'^'    結果: '^^^^abc'

# 原字元:'你好嗎' 寬度: 5 字元:'0' 結果: '00你好嗎'

defnew_rjust

(str1, str2, length)

:

寫乙個自己的index函式,統計指定列表中指定元素的所有下標,如果列表中沒有指定元素返回-1

# 例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0]  元素: 1   結果: 0,4,6  

# 列表: ['趙雲', '郭嘉', '諸葛亮', '曹操', '趙雲', '孫權'] 元素: '趙雲' 結果: 0,4

# 列表: ['趙雲', '郭嘉', '諸葛亮', '曹操', '趙雲', '孫權'] 元素: '關羽' 結果: -1

defindex1

(n,list1=

):list2=

[x for x in

range

(len

(list1)

)if n==list1[x]

]return list2

print

(index1(1,

[1,2

,45,'abc',1

,'你好',1

,0])

)

寫乙個自己的len函式,統計指定序列中元素的個數

# 例如: 序列:[1, 3, 5, 6]    結果: 4

# 序列:(1, 34, 'a', 45, 'bbb') 結果: 5

# 序列:'hello w' 結果: 7

defnew_len

(list1)

: count =

0for word in list1:

count +=

1return count

寫乙個自己的max函式,獲取指定序列中元素的最大值。如果序列是字典,取字典值的最大值

# 例如: 序列:[-7, -12, -1, -9]    結果: -1   

# 序列:'abcdpzasdz' 結果: 'z'

# 序列: 結果: 98

defnew_max

(s):

寫乙個函式實現自己in操作,判斷指定序列中,指定的元素是否存在

# 例如: 序列: (12, 90, 'abc')   元素: '90'     結果: false

# 序列: [12, 90, 'abc'] 元素: 90 結果: true

defnew_in

(list1, s)

:

寫乙個自己的replace函式,將指定字串中指定的舊字串轉換成指定的新字串

# 例如: 原字串: 'how are you? and you?'   舊字串: 'you'  新字串:'me'  結果: 'how are me? and me?'

defnew_replace

(str1,old_str,news)

:

day9 函式作業

編寫乙個函式,交換指定字典的key和value。例如 dict1 dict1 defexchange dict1 param dict1 return list1 value,key for key,value in dict1.items print dict list1 exchange 編寫乙...

day9 函式作業

編寫乙個函式,交換指定字典的key和value。例如 dict1 dict1 defexchange dict1 result print result exchange x 10,y 20,z 30 編寫乙個函式,提取指定字串中所有的字母,然後拼接在一起產生乙個新的字串 例如 傳入 12a bc1...

day9函式作業詳解

2,寫函式,檢查獲取傳入列表或元組物件的所有奇數字索引對應的元素,並將其作為新列表返回給呼叫者。3,寫函式,判斷使用者傳入的物件 字串 列表 元組 長度是否大於5。4,寫函式,檢查傳入列表的長度,如果大於2,將列表的前兩項內容返回給呼叫者。5,寫函式,計算傳入函式的字串中,數字 字母 空格 以及 其...