Python學習筆記 字串小練習

2021-10-21 18:37:00 字數 1819 閱讀 8545

一、編寫乙個程式,接受一行序列作為輸入,並在將句子中的所有字元大寫後列印行。

假設向程式提供以下輸入:

hello world

practice makes perfect

則輸出為:

hello world

practice makes perfect

str1 =

input

("請輸入乙個字串:"

)print

("大寫後的字串為:"

+str1.upper(

))

二、編寫乙個程式,接受一系列空格分隔的單詞作為輸入,並在刪除所有重複的單詞並按字母數字排序後列印這些單詞。

假設向程式提供以下輸入:

hello world and practice makes perfect and hello world again

則輸出為:

again and hello makes perfect practice world

str1 =

input

("請輸入一段以空格為分割的單詞字串:\n"

)list1 = str1.split(

' ')

list2 =

set(list1)

print

(sorted

(list2)

)

三、編寫乙個程式,它將找到1000到3000之間的所有這些數字(均包括在內),這樣數字的每個數字都是偶數。

獲得的數字應以逗號分隔的順序列印在一行上。

dlist =[0

,2,4

,6,8

]def

judge

(i):

while i>0:

k=i%

10if k not

in dlist:

return

false

i=int(i/10)

return

true

for k in

range

(1000

,3000):

if(judge(k)):

print

(k)

四、編寫乙個接受句子的程式,並計算大寫字母和小寫字母的數量。

假設為程式提供了以下輸入:

hello world!

然後,輸出應該是:

大寫例項 1

小寫例項 9

str1 =

input

("請輸入字串:"

)a =

0a =

0for i in

range

(len

(str1)):

if(str1[i]

.isalpha())

:if(str1[i]

>=

'a')

: a+=

1else

: a+=

1print

("字串中大寫字母"

,a,"個,小子字母"

,a,'個'

)

五、編寫乙個程式,計算a + aa + aaa + aaaa的值,給定的數字作為a的值。假設為程式提供了以下輸入:9 然後,輸出應該是: 11106

a = int(input(「請輸入a:」))

print

("a+aa+aaa+aaaa="

,1234

*a)

Python之字串小練

字串 a 3 數字 b 1234 字串可以用單引號表示 c 1 字串也可以用雙引號表示 引導既可以用單引號也可以用雙引號,但是要前後一致 print 列印括號內的內容到控制台 print it s ok.當句子中有單引號時,可以用雙引號,避免語法錯誤 print he said are you ok...

python小筆記 字串

單引號或者雙引號括起來的任意文字 建立 str sunck good 運算 字串連線 str1 sunck str2 good str3 str1 str2 print str3 str3 返回str3 sunck good 輸出重複的字串 str1 good str2 str1 3 print s...

python小筆記 字串2

轉義字元 將一些字元轉換成有特殊含義的字元 eg print sunck n good 返回sunck n good 返回單引號 eg print sunck is good 返回sunck is good eg print sunck is good 返回sunck is good 返回雙引號 e...