python编码-1
help帮助系统,一个好的方法是直接看自带的帮助,尽量不用baidu
help()是进入交互式帮助界面
quit是退出交互式帮助界面 [root@kvm1 python]# python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help() Welcome to Python 2.7! This is the online help utility. If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/. Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam". help> help> quit You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt. 下面是模块,关键字,主题的列表
help> modules Please wait a moment while I gather a list of all available modules... ANSI base64 io sched
BaseHTTPServer bdb itertools screen
Bastion binascii javapackages select
CDROM binhex json selinux
CGIHTTPServer bisect jsonschema semanage
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose descriptions contain the word "spam". help> keywords Here is a list of the Python keywords. Enter any keyword to get more help. and elif if print
as else import raise
assert except in return
help> topics Here is a list of available topics. Enter any topic name to get more help. ASSERTION DEBUGGING LITERALS SEQUENCEMETHODS2
ASSIGNMENT DELETION LOOPING SEQUENCES
ATTRIBUTEMETHODS DICTIONARIES MAPPINGMETHODS SHIFTING
ATTRIBUTES DICTIONARYLITERALS MAPPINGS SLICINGS
导入一个自定义模块
[root@250-shiyan ~]# mkdir python
[root@250-shiyan ~]# cd python/
[root@250-shiyan python]# cat >hello.py
#! /usr/bin/env python
print "hello world"
[root@250-shiyan python]# python hello.py
hello world
[root@250-shiyan python]# ll
total 4
-rw-r--r-- 1 root root 43 Jul 16 12:50 hello.py
[root@250-shiyan python]# chmod 755 hello.py
[root@250-shiyan python]# ./hello.py
hello world
[root@250-shiyan python]# python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
hello world
>>> quit()
[root@250-shiyan python]# ll
total 8
-rwxr-xr-x 1 root root 43 Jul 16 12:50 hello.py
-rw-r--r-- 1 root root 116 Jul 16 12:51 hello.pyc
需求逐渐增加
1.去掉用户名前后的空格 strip()
2.判断用户名不为空
不输入或输入空格都是空 用len()
3.判断用户名是否输错 !=
4.超过3次就退出
需要一个计数器来判断次数
程序是一步步做出来的,这次加一点,下次加一点。
1.第一次只是基本的格式化输出 print "your name is %s" %name
2.第二次加入 strip()方法去掉前后的空格,保证程序的健壮性,来防止用户输入错误。
3.第三次加入while循环,使得用户只能输入正确的aa,才能返回正常,否则不输入或输入错误都不行
[root@kvm1 python]# cat input2.py
#! /usr/bin/env python #name= raw_input("please enter your name: ").strip()
while True:
name= raw_input("please enter your name: ").strip()
if len(name)==0:
print "Empty name,try again:"
continue
elif name != "aa"
print "Error name,try again: %s " %name
continue
break
age=int(raw_input("please enter your age: "))
sex= raw_input("your sex is: ")
dep= raw_input("which department: ")
#message = '''Information of the company staff:
# Name:%s
# Age:%d
# Sex:%s
# Dep:%s
# ''' % (name,age,sex,dep)
#print message if name != "aa":
print "you are not in user list"
else:
print "welcome you are login"
制作tab补全
centos7是下面这个目录,ubuntu可能不一样
[root@kvm1 site-packages]# pwd
/usr/lib/python2.7/site-packages
[root@kvm1 site-packages]# vi tab.py
#!/usr/bin/env python
# python startup file
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter [root@kvm1 site-packages]# python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import tab
>>> sys.
sys.__class__( sys.__subclasshook__( sys.exitfunc( sys.path_importer_cache
[root@kvm1 site-packages]# ll tab.py
tab.py tab.pyc
进入python,import tab一下,就有了tab.pyc这个模块了
>>> import os shutil
>>> os.getcwd()
'/root/code/python'
>>> os.listdir("/home")
['zf', 'img', 'iso', 'docker']
>>> os.path.isfile("/tmp")
False
>>> os.path.isfile("input.py")
True
>>> os.path.isabs("input.py")
False
>>> os.path.isabs("/root/code/python/input.py")
True
>>> os.path.split("/root/code")
('/root', 'code')
>>> os.system("free")
total used free shared buff/cache available
Mem: 32657352 16457992 6302376 229644 9896984 15655708
Swap: 14352380 0 14352380
0
>>> os.linesep
'\n'
>>> os.name
'posix' >>> import tab
>>> from os import system
>>> system("df -h")
python 将用户输入录入到sqlite3数据库中,不过这个脚本有点问题,自动创建库,因为首次要建表,第二次录入时会报错,所以应该加一个判断表是否存在的语句块,然后再插入数据,查询数据时,有几行查几行,也可以一次查完(根据代码适度调整吧)
[root@kvm1 python]# cat input3.py
#! /usr/bin/env python import sqlite3 name= raw_input("please enter your name: ")
age=int(raw_input("please enter your age: "))
sex= raw_input("your sex is: ")
dep= raw_input("which department: ") # test.db is a file in the working directory.
conn = sqlite3.connect("test.db")
c = conn.cursor()
# create tables
c.execute('''CREATE TABLE staff
(name string,
age int,
sex string,
dep string)''')
# save the changes
conn.commit() #staffs = [("a",10,"male","caiwu"),
# ("b",15,"female","hr"),
# ("c",20,"male","it")] # execute "INSERT"
#c.execute("INSERT INTO staff VALUES (,age,sex,dep)")
# using the placeholder
c.execute("INSERT INTO staff VALUES (?, ?, ?, ?)", (name,age,sex,dep)) #c.execute('UPDATE staff SET price=? WHERE id=?',(1000, 1))
#c.execute('DELETE FROM staff WHERE id=2')
#c.execute('DROP TABLE staff')
# execute multiple commands
#c.executemany('INSERT INTO staff VALUES (?, ?, ?, ?)', staffs)
conn.commit()
#SQL语句中的参数,使用"?"作为替代符号,并在后面的参数中给出具体值。这里不能用Python的格式化字符串,如"%s",因为这一用法容易受到SQL注入攻击。 c.execute('SELECT * FROM staff')
print(c.fetchone())
print(c.fetchone()) # retrieve all records as a list
#c.execute('SELECT * FROM staff')
#print(c.fetchall()) # iterate through the records
#for row in c.execute('SELECT name, price FROM book ORDER BY sort'):
# print(row) # close the connection with the database
conn.close()
全局替换,注意print aa,这个逗号,不加的话,最后修改后的list.txt格式不正确
[root@kvm1 python]# python rep.py
[root@kvm1 python]# cat list.txt
1 zhou aa-1 15897638976
2 wu feaa 18946578291
3 zheng aa-1 02134578129
4 wang feaa 01098452345
5 feng feaa 02987654890
6 cheng feaa 15771543637
7 chu aa-1 18691234578
8 wei aa-1 18097643789
9 li aa-1 17654893092 [root@kvm1 python]# cat rep.py
#! /usr/bin/env python import fileinput
for line in fileinput.input("list.txt",inplace=1):
aa=line.replace("male","aa")
print aa,
将字符串转成列表
>>> name
['alex', 'fog', 4, 'wo', 'wo']
>>> name.count('wo')
2
>>> 'fog' in name
True
>>> 'fog1' in name
False 将字符串转成列表,默认是以空格为分隔符的,也可以以某个符号为分隔符例如=
>>> a='wowiewoewie'
>>> a.split()
['wowiewoewie']
>>> a='w o w i ew o ew ie'
>>> a.split()
['w', 'o', 'w', 'i', 'ew', 'o', 'ew', 'ie']
>>> a='w o = w i ew = o ew ie'
>>> a.split('=')
['w o ', ' w i ew ', ' o ew ie']
>>> b=a.split('=')
>>> b
['w o ', ' w i ew ', ' o ew ie']
一个购物车程序,用到了列表
[root@kvm1 python]# cat shop.py
#! /usr/bin/env python import sys
products=['car','phone','food','colths','bicyle']
prices=[5000,2010,202,120,549]
shop=[]
while True:
try:
salary=int(raw_input("please input your money "))
break
except ValueError:
print "please input a number,not string."
while True:
print "the have to the shop,please choose one to buy"
for p in products:
print "%s,%s" %(p,prices[products.index(p)])
choice=raw_input("please input one item to buy: ")
F_choice=choice.strip()
if F_choice =='quit':
print "you have bought these things: %s" % shop
sys.exit()
if F_choice in products:
product_price_index=products.index(F_choice)
product_price=prices[product_price_index]
print "%s $%s" %(F_choice,product_price)
if salary > product_price:
shop.append(F_choice)
print "added %s into your shop list" %F_choice
salary =salary - product_price
print "salary is left: $",salary
else:
if salary < min(prices):
print "rest of money cant buy anything"
print "you have these things: %s" % shop
sys.exit()
else:
print "sorry,you cant affor this thing"
从文件中读入数据,并将其转为列表
将文本文件转成列表
[root@kvm1 python]# cat aa.txt
car 1000
phone 500
colth 231
coffe 59
bicyle 400
[root@kvm1 python]# cat b.py
#! /usr/bin/env python products = []
prices = [] f = file("aa.txt")
for line in f.readlines():
p = line.split()[0]
pri = int(line.split()[1])
products.append(p)
prices.append(pri)
print products
print prices [root@kvm1 python]# python b.py
['car', 'phone', 'colth', 'coffe', 'bicyle']
[1000, 500, 231, 59, 400]
将列表导出到一个文件中
[root@kvm1 python]# cat pat.py
import sys
f=open('pat.txt','w') for i in sys.path:
f.write(i+'\n') f.close()
[root@kvm1 python]# python pat.py
[root@kvm1 python]# cat pat.txt
/root/code/python
/usr/lib/python2.7/site-packages/mechanize-0.2.5-py2.7.egg
/usr/lib64/python27.zip
/usr/lib64/python2.7
/usr/lib64/python2.7/plat-linux2
/usr/lib64/python2.7/lib-tk
/usr/lib64/python2.7/lib-old
/usr/lib64/python2.7/lib-dynload
/usr/lib64/python2.7/site-packages
/usr/lib64/python2.7/site-packages/gtk-2.0
/usr/lib/python2.7/site-packages sys.path这个是模块的搜索路径,如果都没有,就报错。
所以可以将自己的.py文件放入以下任何一个目录中,就可随便导入了,并生成pyc文件
python编码-1的更多相关文章
- (转载) 浅谈python编码处理
最近业务中需要用 Python 写一些脚本.尽管脚本的交互只是命令行 + 日志输出,但是为了让界面友好些,我还是决定用中文输出日志信息. 很快,我就遇到了异常: UnicodeEncodeError: ...
- Python 编码简单说
先说说什么是编码. 编码(encoding)就是把一个字符映射到计算机底层使用的二进制码.编码方案(encoding scheme)规定了字符串是如何编码的. python编码,其实就是对python ...
- Python之路3【知识点】白话Python编码和文件操作
Python文件头部模板 先说个小知识点:如何在创建文件的时候自动添加文件的头部信息! 通过:file--settings 每次都通过file--setings打开设置页面太麻烦了!可以通过:View ...
- python编码规范
python编码规范 文件及目录规范 文件保存为 utf-8 格式. 程序首行必须为编码声明:# -*- coding:utf-8 -*- 文件名全部小写. 代码风格 空格 设置用空格符替换TAB符. ...
- 【转】python编码的问题
摘要: 为了在源代码中支持非ASCII字符,必须在源文件的第一行或者第二行显示地指定编码格式: # coding=utf-8 或者是: #!/usr/bin/python # -*- coding: ...
- 【转】python编码规范
http://blog.csdn.net/willhuo/article/details/49300441 决定开始Python之路了,利用业余时间,争取更深入学习Python.编程语言不是艺术,而是 ...
- python 编码 UnicodeDecodeError
将一个py脚本从Centos转到win运行,出错如下: UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: il ...
- Python编码/文件读取/多线程
Python编码/文件读取/多线程 个人笔记~~记录才有成长 编码/文件读取/多线程 编码 常用的一般是gbk.utf-8,而在python中字符串一般是用Unicode来操作,这样才能按照单个字 ...
- 关于Python编码,超诡异的,我也是醉了
Python的编码问题,真是让人醉了.最近碰到的问题还真不少.比如中文文件名.csv .python对外呈现不一致啊,感觉好不公平. 没图说个JB,下面立马上图. 我早些时候的其他脚本,csv都是 ...
- 规范的python编码
规范的 python 编码令人赏心悦目,令代码的表达逻辑更清晰,使得工程代码更容易被维护和交流: 编码规范包括对于代码书写格式的约束,不良语法的禁用和推荐的编码手法,下面做些简要的描述: 1. 代码规 ...
随机推荐
- Evolutionary Computing: 1. Introduction
Outline 什么是进化算法 能够解决什么样的问题 进化算法的重要组成部分 八皇后问题(实例) 1. 什么是进化算法 遗传算法(GA)是模拟生物进化过程的计算模型,是自然遗传学与计算机科学相互结合的 ...
- [分享] WIN7x64封装体积小于4G制作过程
raymond 发表于 2015-11-1 18:27:17 https://www.itsk.com/thread-359041-1-1.html 前人栽树,后人乘凉!感谢各位大神的作品!我只是按部 ...
- C语言输出时的各种%
d 以十进制形式输出带符号整数(正数不输出符号) o 以八进制形式输出无符号整数(不输出前缀O) x 以十六进制形式输出无符号整数(不输出前缀OX) u 以十进制形式输出无符号整数 f 以小 ...
- BZOJ2095 [Poi2010]Bridges
首先二分答案...然后这张图变成了有一些有向边,有一些无向边 然后就是混合图欧拉回路的判断 我们知道如果是有向图,它存在欧拉回路的等价条件是所有点的出度等于入度 对于混合图...先不管有向边,把无向边 ...
- [原创]C#按比例缩放窗体控件及字体
按照比例缩放窗体控件及字体,如需等比例缩放,只需将x,y的比例设置成相同即可. 为了减小误差,建议使用原始尺寸来计算比例. private float X, Y; private bool b = f ...
- 我也来SplashScreen
SplashScreen,就是平时我们说的溅射屏幕,任何一个做过客户端程序的coder应该对它都不陌生,因为它能提升用户体验,让软件看上去更美.SplashScreenForm通常进入程序时是打开,主 ...
- Linux下SVN命令
一下内容转载于:http://blog.chinaunix.net/space.php?uid=22976768&do=blog&id=1640924.这个总结的很好~ windows ...
- JavaScript本地对象 内置对象 宿主对象
在ECMAScript中,所有对象并非同等创建的. 一般来说,可以创建并使用的对象有3种:本地对象.内置对象和宿主对象. 1. 本地对象 ECMA-262把本地对象(native obje ...
- android 第一个程序的编写
移通152余继彪 需求分析:输入两个数字,让他们相乘,然后得出结果 首先建立一个android项目 在 layout中建立第一个界面 该界面有四个组件,两个editText 一个TextView,一个 ...
- spirng定时任务的两种配置:注解和xml
一 使用注解Task 1.在applicationContext.xml中配置 <?xml version="1.0" encoding="UTF-8"? ...