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)