python (1) 还不是大全的小问题

2023-06-20,

1.pythone 获取系统时间
import datetime
nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#现在
pastTime = (datetime.datetime.now()-datetime.timedelta(hours=1)).strftime('%Y-%m-%d %H:%M:%S')#过去一小时时间
afterTomorrowTime = (datetime.datetime.now()+datetime.timedelta(days=2)).strftime('%Y-%m-%d %H:%M:%S')#后天
tomorrowTime = (datetime.datetime.now()+datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')#明天
print('\n',nowTime,'\n',pastTime,'\n',afterTomorrowTime,'\n',tomorrowTime)

2.格式化输出
str="%s:%d"%("hello-world", 123)

 3.if else

 x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')

 4.字符串包含

第一种方法:in

string = 'helloworld'

if 'world' in string:

  print 'Exist'

else:

  print 'Not exist'

第二种方法:find

string = 'helloworld'

if string.find(’world‘) == 5: #5的意思是world字符从那个序开始,因为w位于第六个,及序为5,所以判断5

  print 'Exist'

else:

  print 'Not exist'

第三种方法:index,此方法与find作用类似,也是找到字符起始的序号

if string.index(’world‘) > -1: #因为-1的意思代表没有找到字符,所以判断>-1就代表能找到

  print 'Exist'

如果没找到,程序会抛出异常

  5.字符串分割

st0= 'iisongiiihuaniiiigongi'
print(st0.split('i'))
结果为:
['', '', 'song', '', '', 'huan', '', '', '', 'gong', '']

  6.python 不支持switch

  查看Python官方:PEP 3103-A Switch/Case Statement, 实现Switch Case需要被判断的变量是可哈希的和可比较的,

  与Python倡导的灵活性有冲突。在实现上,优化不好做,可能到最后最差的情况汇编出来跟If Else组是一样的。

  Python没有支持switch。

 7.python 实现结构体
应用场景:在类中只用globa引用外部的多个变量
# filename:p.py
class Employee:
pass
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
>>> import p
>>> p.john
<p.Employee instance at 0xb71f50ac>
>>> p.john.name
'John Doe'
>>> p.john.dept
'computer lab'
>>> p.john.salary
1000

  8.转换

int(x [,base ])         将x转换为一个整数
long(x [,base ]) 将x转换为一个长整数
float(x ) 将x转换到一个浮点数
complex(real [,imag ]) 创建一个复数
str(x ) 将对象 x 转换为字符串
repr(x ) 将对象 x 转换为表达式字符串
eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s ) 将序列 s 转换为一个元组
list(s ) 将序列 s 转换为一个列表
chr(x ) 将一个整数转换为一个字符
unichr(x ) 将一个整数转换为Unicode字符
ord(x ) 将一个字符转换为它的整数值
hex(x ) 将一个整数转换为一个十六进制字符串
oct(x ) 将一个整数转换为一个八进制字符串
chr(65)='A'
ord('A')=65
int('2')=2;
str(2)='2'

  9.创建文件服务器

    执行命令python -m SimpleHTTPServer 端口号, 不填端口号则默认使用8000端口。 

 

python (1) 还不是大全的小问题的相关教程结束。

《python (1) 还不是大全的小问题.doc》

下载本文的Word格式文档,以方便收藏与打印。