python基础——变量、注释、字符串操作

python脚本第一行

#!/usr/bin/python
#!/usr/bin/env python    #自动选择最新的python环境

python3.x 默认utf-8

python2.x 默认ascii编码,中文会乱码,第二行加入

# -*- coding: utf-8 -*-

 

注释

单行注释,与shell相同,#开头
多行注释,三个引号,单双引号都可

#code

"""
code1
code2
"""

'''
code3
code4
'''

 

 

变量

变量名:
1.只能是一个词;
2.只能包含字母、数字和下划线;
3.不能以数字开头。
4.关键字不能声明为变量名

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 
'global', 'if', 'import', 'in','is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

两种变量名格式:

name_of_campany    下划线式
NameOfCampany    驼峰式

变量赋值:

a = 'abc'
b = '123'

a,b = 'abc','123'

用_跳过变量:

_, a = (1, 2)
print(a)
# 显示2

 

 

 

 

字符串

s="hello world"
print(s)
print(len(s))  #获取字符串长度,算空格

字符串索引
print(s[0])  #第1个字符
print(s[10])  #第11个字符

字符串切片
s[startIndex:pastIndex],startIndex起始索引,pastIndex终点索引
print(s[0:2])
print(s[2:4])
print(s[6:])  #6到结束
print(s.center(40,'-'))  #字符串长度40,左右用-填充
print(s.ljust(40,'-'))  #s在左,右边用-填充
print(s.rjust(40,'-'))  #s在右,左边用-填充

 

字符串操作
s = "hello python"
print(s + ' ' + s)  #用+连接字符串
print(s.replace('hello', 'thanks'))  #修改字符串
print(s.find('l'))  #在字符串中找l的索引
print(s.upper())  #变大写
print(s.lower())  #变小写

sentence = "The cat is brown"
q = "cat"

if q == sentence.strip():  #strip()去掉空白
print('strings equal')  #用==判断字符串是否相等

if q in sentence:
print(q + " found in " + sentence)  #用in判断字符串是否包含

tmp=sentence.split(" ")  #把字符串分割成列表
print(tmp)
print("|".join(tmp))  #把列表合成字符串

 

转义字符
\n,\t,\",\',\\
str1 = "In Python,\nyou can use special characters in strings.\nThese special characters can be..."
print(str1)

str2 = "The word \"computer\" will be in quotes."
print(str2)

 

占位符%

%s 字符串, %d 数字

name = "ss"
print("i am %s " % name)
name=input("姓名:")
age=int(input("年龄:"))
job=input("职业:")

msg='''
----------------
个人信息
姓名:%s
年龄:%d
职业:%s
----------------
'''% (name,age,job)
print(msg)


msg='''
----------------
个人信息
姓名:%s
年龄:%d
职业:%s
----------------
'''
print(msg % (name,age,job))

%f 浮点数

s1 = "%f" %1.12345678    #默认保留6位小数四舍五入
s2 = "%.2f" %1.12345678    #保留2位小数四舍五入,必须加.
print(s1)
print(s2)

用字典的key占位

t = {'name':'abc','age':123}
s = "haha %(name)s %(age)d" %t
print(s)

%%,如果字符串中有占位符,需要用两个%表示一个%

print("aaa %")    #无占位符
print("%s %%" % "aaa")    #有占位符,需要两个%才能显示一个%

 

format

 

msg1="hello {name},i'm {age}."
print(msg1.format(name="ss",age=29))

msg2="hello {0},i'm {1}."
print(msg2.format("ss",29))

n3={'name':'ss','age':29}
msg3="my name is {name} and age is {age}"
print(msg3.format_map(n3))

s1 = "----{name:s}_____{age:d}=======".format(name="ss",age=123)
print(s1)
s2 = "-----{:*^20s}====={:*^10d}".format("ss",123)
#^表示居中,20表示宽度,:*表示用*填充空白
print(s2)
s3 = "{:.2%}".format(0.23)  #自动百分数,.2表示保留两位
print(s3)
s1 = "i am {0},age {1}".format("ss",123)
print(s1)
s2 = "i am {0},age {1}".format(*["ss",123])    #传列表
print(s2)
s3 = "i am {name},age {age}".format(**{"name":"ss","age":123})    #传字典
print(s3)

更多字符串格式化内容 http://www.cnblogs.com/wupeiqi/articles/5484747.html 

 

判断

age=input("your age:")
if age.isdigit(): #判断输入的是否是数字
    age=int(age)
else:
    print("请输入数字~")
name="ss123abc"
print(name.isalnum())  #判断是否有特殊字符,无特殊字符为True
print(name.isalpha())    #判断是否只包含字母
print(name.isdecimal())    #只包含数字字符
print(name.isspace())    #只包含空格,制表符和换行,非空
print(name.istitle())    #大写字母开头,后面都是小写字母
print(name.endswith('abc'))  #判断是否以abc结束
print(name.startswith('ss'))  #判断是否以ss开头

 

字符串转列表或字典

import json
s="[11,22,33,44]"
print(s,type(s))
n=json.loads(s)
print(n,type(n))

"""
用json把字符串改变成字典,字符串必须用双引号
"{"k1":"v1"}"
"""

 

posted @ 2016-08-19 15:31  沄持的学习记录  阅读(200)  评论(0)    收藏  举报