1、輸入字符串,分別字符串中含有數字、字母、空格和其它字符個數。
def
findstr
(
*
param
)
:
chars
=
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
nums
=
'0123456789'
space
=
' '
count_char
=
0
count_num
=
0
count_sp
=
0
count_sym
=
0
for
i
in
x
:
if
i
in
chars
:
count_char
+=
1
elif
i
in
nums
:
count_num
+=
1
elif
i
==
space
:
count_sp
+=
1
else
:
count_sym
+=
1
print
(
"有英文字母%d個,數字%d個,空格%d個,其它字符%d個"
%
(
count_char
,
count_num
,
count_sp
,
count_sym
)
)
x
=
str
(
input
(
"請輸入字符串"
)
)
findstr
(
x
)
2、統計一個長度為2的子字符串在另一個字符串中出現的次數:
def
findstr
(
x
,
y
)
:
result
=
[
]
length
=
len
(
x
)
count
=
0
for
i
in
range
(
length
-
1
)
:
result
.
append
(
x
[
i
:
i
+
2
]
)
for
i
in
result
:
if
y
==
i
:
count
+=
1
return
count
x
=
str
(
input
(
"字符串"
)
)
y
=
str
(
input
(
"子字符串"
)
)
print
(
findstr
(
x
,
y
)
)
3、定義一個函數,求兩個整數的最大公約數:
def
gcd
(
x
,
y
)
:
result
=
0
result1
=
[
]
if
x
>=
y
:
result
=
y
else
:
result
=
x
for
i
in
range
(
1
,
result
+
1
)
:
if
x
%
i
==
0
and
y
%
i
==
0
:
result1
.
append
(
i
)
return
max
(
result1
)
print
(
gcd
(
12
,
8
)
)
4、自己定義一個min()函數,來查看它的實現原理:
def
min
(
x
)
:
result
=
x
[
0
]
for
i
in
x
:
if
result
<=
i
:
continue
else
:
result
=
i
return
result
min
(
[
1
,
2
,
3
]
)
5、定義一個sum()函數,如果不是參數不是整數或浮點數自動略過
def
sum
(
x
)
:
result
=
0
for
i
in
x
:
if
(
type
(
i
)
==
int
)
or
(
type
(
i
)
==
float
)
:
result
+=
i
else
:
continue
return
result
a
=
[
1
,
2
,
3
]
print
(
sum
(
a
)
)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
