幾段Python小程式

2022-07-09 23:51:13 字數 809 閱讀 8016

第乙個需求是需要生成一些隨機的時間,例如需要隨機生成從一年前到現在的一些時間,剛開始折騰了半天,最後的**如下:

from datetime import timedelta

from datetime import date

import random

(datetime.datetime.now()-datetime.timedelta(seconds=random.randrange((datetime.timedelta(days=365)).total_seconds()))).strftime("%y-%m-%d %h:%m:%s")

原來寫python程式設計到輸出或轉字串的時候都是直接用%,但這次稍微花了一些時間,學習了一下format,現在是了。看來以後要轉變寫程式的方式了。具體的語法其實和c的printf也很類似,最簡單的乙個例子如下,這個函式可以從start-end之間選取乙個隨機數,然後輸出為strlen長度的字串,長度不足前面補0:

def gen_range_data(start,end,strlen):

return '}'.format(num=random.randrange(start,end),width=strlen)

python的string裡自帶了好多預定義變數,非常好用,比如說所有的大寫字母,所有的小寫字母,數字等等,有了這些就可以更快更方便的寫出很多功能,例如隨機選擇乙個大寫字母可以用下面這行程式來寫:

return random.choice(string.ascii_uppercase)

python實現小程式 python實現小程式

1 楊輝三角形python實現 1 11 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 楊輝三角形 def triangel n l 1 定義乙個list 1 while true yield l 列印出該list l l x l x 1 for x in range le...

python練習小程式

1.今年是否為閏年 import time thisyear time.localtime 0 print time.localtime if thisyear 400 0 or thisyear 4 0 and thisyear 100!0 print this year s is leap ye...

python實現小程式

1 楊輝三角形python實現 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 楊輝三角形 def triangel n l 1 定義乙個list 1 while true yield l 列印出該list l l x l x 1 for x in range...