0x00 移除字符串中字符
str = input("請輸入一個字符串:")
n = int(input("請輸入要移除的字符位置:"))
print("原始字符串爲:" + str)
new_str = ""
for i in range(0,len(str)):
if i != n:
new_str = new_str + str[i]
print("字符串移除後爲:" + new_str)
0x01 判斷子字符串是否存在
str = input("請輸入一個字符串:")
sub_str = input("請輸入子字符串:")
if sub_str in str:
print("子字符串存在!")
else:
print("子字符串不存在!")
0x02 正則表達式提取URL
import re
def Find(string):
# findall() 查找匹配正則表達式的字符串
url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
return url
string = 'Google 的網頁地址爲:https://www.google.com'
print("Urls: ", Find(string))
0x03 字符串翻轉
str = input("請輸入一個字符串:")
print("初始字符串爲:" + str)
print("翻轉字符串爲:" + str[::-1])
0x04 字符串切片
def rotate(input,d):
Lfirst = input[0 : d]
Lsecond = input[d :]
Rfirst = input[0 : len(input)-d]
Rsecond = input[len(input)-d : ]
print( "頭部切片翻轉 : ", (Lsecond + Lfirst) )
print( "尾部切片翻轉 : ", (Rsecond + Rfirst) )
if __name__ == "__main__":
str = input("請輸入一個字符串:")
d = int(input("請輸入切片長:"))
rotate(str,d)
0x05 字典排序
def dictionairy():
# 聲明字典
key_value ={}
# 初始化
key_value[2] = 56
key_value[1] = 2
key_value[5] = 12
key_value[4] = 24
key_value[6] = 18
key_value[3] = 323
print ("按鍵(key)排序:")
# sorted(key_value) 返回一個迭代器
# 字典按鍵排序
for i in sorted (key_value) :
print ((i, key_value[i]), end =" ")
def main():
# 調用函數
dictionairy()
# 主函數
if __name__=="__main__":
main()
0x06 計算字典值之和
def Sum(myDict):
sum = 0
for i in myDict:
sum = sum + myDict[i]
return sum
dict = {'a':100,'b':200,'c':300}
print("Sum:",Sum(dict))
0x07 移除字典鍵值對
test_dict = {'a':1,'b':2,'c':3,'d':4}
print("字典移除前:" + str(test_dict))
del test_dict['d']
print("字典移除後:" + str(test_dict))
0x08 合併字典
def Merge(dict1,dict2):
dict3 = {**dict1, **dict2}
return dict3
dict1 = {'a':1,'b':2}
dict2 = {'c':3,'d':4}
dict3 = Merge(dict1,dict2)
print(dict3)
0x09 時間戳轉換
import time
a1 = "2019-5-10 23:40:00"
# 先轉換爲時間數組
timeArray = time.strptime(a1, "%Y-%m-%d %H:%M:%S")
# 轉換爲時間戳
timeStamp = int(time.mktime(timeArray))
print(timeStamp)
# 格式轉換 - 轉爲 /
a2 = "2019/5/10 23:40:00"
# 先轉換爲時間數組,然後轉換爲其他格式
timeArray = time.strptime(a2, "%Y/%m/%d %H:%M:%S")
otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
print(otherStyleTime)