python1

数据类型:
[root@foundation21 ~]# python
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'hello' is not defined
>>> s = "hello"
>>> s[1:]
'ello'
>>> s[:5]
'hello'
>>> s[1:5]
'ello'
>>> s[1:4]
'ell'
>>> s[:-1]
'hell'
>>> s[-5:]
'hello'
>>>
In [22]: "Hello".istitle()
Out[22]: True

In [23]: "hello".istitle()
Out[23]: False

In [24]: s = "Westos"

In [25]: s.istitle()
Out[25]: True
In [26]: s.
s.capitalize  s.format      s.isupper     s.rindex      s.strip
s.center      s.index       s.join        s.rjust       s.swapcase
s.count       s.isalnum     s.ljust       s.rpartition  s.title
s.decode      s.isalpha     s.lower       s.rsplit      s.translate
s.encode      s.isdigit     s.lstrip      s.rstrip      s.upper
s.endswith    s.islower     s.partition   s.split       s.zfill
s.expandtabs  s.isspace     s.replace     s.splitlines  
s.find        s.istitle     s.rfind       s.startswith
In [28]: s = "hello"

In [29]: s.capitalize()
Out[29]: 'Hello'

In [30]: s
Out[30]: 'hello'
In [31]: s.center(10,"#")
Out[31]: '##hello###'

In [32]: s.center(10,'#')  #####S.center(width[, fillchar]) -> string
Out[32]: '##hello##
判断变量名是否合法:
代码:
import  string

name = raw_input("changename: ")
if name[0] not in string.letters + "_":
    print  "the first number is errot"
    exit(0)
else:
    for item in name[1:]:
        if item not in string.letters+"_"+string.digits:
            print "changename is error"
            exit(0)
print "changename is error"


####s.strip
In [6]: s = "     hello     "

In [7]: print s
     hello     

In [8]: s.st
s.startswith  s.strip       

In [8]: s.strip()
Out[8]: 'hello'

In [9]: s.lstrip()
Out[9]: 'hello     '

In [10]: s.rstrip()
Out[10]: '     hello'

In [11]: "hello     world".strip()
Out[11]: 'hello     world'

习题:
myint= raw_input("input english : ")

myint1 = myint.split()


print len(myint1)

一 数据类型
1. 背景
面试题案例: 123和“123”一样么?
- 从数字角度讲
- 从程序语言的识别来讲
>>> a = 123
>>> stra = "123"
>>> a == stra
False
>>> print a
123
>>> print stra
123
>>> a + stra
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
数字
整型>>> num1 = 123
>>> type(num1)
<type 'int'>
>>> type(123)
<type 'int'>
长整形
>>> num2 = 999999999999999
>>> type(num2)
<type 'int'>
强制定义为长整型: num3 = 123L
>>> num3 = 123L
>>> type(num3)
<type 'long'>
浮点型:表示小数
>>> f1 = 12
>>> type(f1)
<type 'int'>
>>> f2 = 12.0
>>> type(f2)
<type 'float'>
复数类型:python对复数提供内嵌支持,eg: 3.14j, 8.32e-36j
>>> c = 3.14
>>> type(c)
<type 'float'>
>>> c = 3.14j
>>> type(c)
<type 'complex'>
字符串
字符串的定义
# 字符串定义的第一种方式:
>>> str1 = 'our company is westos'
 
# 字符串定义的第二种方式:
>>> str2 = "our company is westos"
 
# 字符串定义的第三种方式:
>>> str3 = """our company is westos"""
 
>>> type(str1)
<type 'str'>
>>> type(str2)
<type 'str'>
>>> type(str3)
<type 'str'>
 
 
>>> say = 'let\'s go'>>> say
"let's go"
>>> say = "let's go "
>>> say
"let's go "
转义符号
>>> mail = "tom: hello i am westos "
>>> print mail
tom: hello i am westos
>>> mail = "tom:\n hello\n i am westos "
>>> print mail
tom:
hello
i am westos
三重引号
块注释
函数的doc文档
字符串格式化
>>> mail = """tom:
...     i am jack
...     good luck
... """
>>> print mail
tom:
    i am jack
    good luck
>>> mail
'tom:\n\ti am jack\n\tgood luck\n'字符串索引
>>> a = 'abcde'
>>> type(a)
<type 'str'>
>>> a[0]
'a'
>>> a[1]
'b'
>>> a[3]
'd'
>>> a[0]+a[1]
'ab'
>>> a[0]+a[2]
'ac'
字符串切片
>>> a
'abcde'
>>> a[1:5:2]
'bd'
>>> a[1:5]        //代表切片取出第2个到第4个
'bcde'
>>> a[:5]
'abcde'
>>> a[4:]
'e'
>>> a[4:1]            //python中默认是从左向右取值
''
>>> a[4:1:-1]        //当步长为-1时,从右向左取值
'edc'
>>> a[:]'abcde'
 
 
>>> a[-1]
'e'
>>> a[-4:-1]        //代表倒数第2个到倒数第4个切片
'bcd'
>>> a[-2:-4]
''
>>> a[-2:-4:1]
''
>>> a[-2:-4:-1]
'dc

列表
列表是可变类型的序列,而元组与字符串是不可变类型的序列
1.列表的定义:
In [21]: list = []  # 定义一个空列表

In [22]: type(list)# 通过python的内置函数type查看list的数据类型
Out[22]: list

In [23]: print list
[]
In [24]: list1 = ["fentiao","5","male"]# 定义一个包含元素的列表,元素可以是任意类型,包括数值类型,列表,字符串等均可。 此处定义一列表,名为list1

In [25]: print list1
['fentiao', '5', 'male']

 
2 此处我查看下标为1元素的值,重新给这个索引赋值,我们发现列表的元素是可变的;
In [36]: list1
Out[36]: ['fendai', 4, 'female']

In [37]: list1[1]
Out[37]: 4

In [38]: list1[1]=7

In [39]: list1
Out[39]: ['fendai', 7, 'female']

列表的操作:理解"对象=属性+方法"与类
3.列表的索引和切片
# 列表的索引:下标是从0开始计算,比如list[0]读取的是列表的第1个元素;
  list[-1]读取的是列表的倒数第1个元素;
In [39]: list1
Out[39]: ['fendai', 7, 'female']

In [40]: list1[0]
Out[40]: 'fendai'

In [41]: list1[-1]
Out[41]: 'female'

# 列表的切片
>>> list1[:]            //通过切片的方式可以实现列表的复制
['fentiao', 5, 'male']
# 0代表从哪个索引开始切片,3代表切片到哪个位置,并且不包含第三个索引,2代表切片的步长;
>>> list1[0:3:2]
['fentiao', 'male']
In [42]: list1[:]
Out[42]: ['fendai', 7, 'female']

In [43]: list1[1:]
Out[43]: [7, 'female']

In [44]: list1[:2]
Out[44]: ['fendai', 7]

列表的添加:
In [45]: list1.
list1.append   list1.extend   list1.insert   list1.remove   list1.sort
list1.count    list1.index    list1.pop      list1.reverse  

In [45]: list1.append("cat")#####在列表的末尾添加

In [46]: list1
Out[46]: ['fendai', 7, 'female', 'cat']
In [48]: help(list1.append)   ####查看list1.append的使用方法;
列表的长度:
In [51]: len(list1)  #####查看列表的长度
Out[51]: 4

In [52]: list1
Out[52]: ['fendai', 7, 'female', 'cat']


列表的删除:
方法一:
>>> list1.remove("cat")>>> list1
['fendai', 5, 'male']
方法二:
>>> list1.remove(list1[3])
>>> list1
['fendai', 5, 'male']
方法三:
>>> del(list1[3])
>>> list1
['fendai', 5, 'male']
列表的修改
>>> list1
['fentiao', 5, 'male', 'cat']
>>> id(list1)
140205776057408
>>> list1[0] = "fendai"
>>> id(list1)
140205776057408
列表元素的查找:var in list
练习
打印1-100中所有的偶数
打印1-100中所有的奇数

In [8]: range (2,100,2)
In [9]: range (1,100,2)
元组tuple
元组的定义:
定义空元组
tuple = ()
定义单个值的元组
tuple = (fentiao,)
一般的元组
tuple = (fentiao, 8, male)
为什么需要元组?
>>> userinfo1 = "fentiao 4 male"
>>> userinfo2 = "westos 10 unknown"
>>> userinfo1[:7]
'fentiao'
>>> userinfo2[:6]
'westos'
字符串中操作提取姓名/年龄/性别的方式不方便,诞生元组与列表这两个数据类型
>>> t1 = ("fentiao",4,"male")>>> t2 = ("westos", 10, "unknown")
>>> type(t1)
<type 'tuple'>
>>> type(t2)
<type 'tuple'>
>>> t1[0]
'fentiao'
>>> t2[0]
'westos'
>>> t2[0:2]
('westos', 10)
不能对元组的值任意更改
>>> t1
('fentiao', 4, 'male')
>>> t1[1] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
对元组分别赋值,引申对多个变量也可通过元组方式分别赋值
>>> t1
('fentiao', 4, 'male')
>>> name,age,gender=t1
>>> print name,age,gender
fentiao 4 male
 
>>> a,b,c=(1,2,3)
>>> print a,b,c
1 2 3
注意:C语言中,定义一类型,必须先开辟一存储空间,当后期重新赋值时也一定是整型的;
python中,先在内存上存储数据后,再通过标签去引用。不同的字符串占用不同的存储空间。
>>> str1
'12345'
>>> id(str1)
140205776037520
>>> str1 = "abcde"
>>> id(str1)
140205776037424
>>> str2 = "12345"
>>> id(str2)
140205776037520



In [9]: yuan = (1,2,3,4)

In [10]: type(yuan)
Out[10]: tuple

In [11]: yuan[1]
Out[11]: 2
In [14]: yuan[:]
Out[14]: (1, 2, 3, 4)

In [15]: yuan[1:]
Out[15]: (2, 3, 4)

In [16]: yuan[:2]
Out[16]: (1, 2)
In [17]: name,age,gender=("fentiao",5,"male")

In [18]: print name
fentiao

In [19]: print age
5

In [20]: print ge
gender       get_ipython  getattr      

In [20]: print gender
male

In [21]: print name,age,gender
fentiao 5 male
In [25]: t = (1)

In [26]: type(t)
Out[26]: int

In [27]: type('hello')
Out[27]: str

In [28]: t = ('hello')

In [29]: type(t)
Out[29]: str
In [30]: t = (1,)

In [31]: type(t)
Out[31]: tuple




stack = []
def pushstack():
    item = raw_input('new item:')
    stack.append(item)
def  popstack():
     if len(stack)== 0:
         print "can not pop from empty item"
     else:
         print "%s pop from stack "%stack .pop()
def viewstack():
    print stack

def showmenu():
     pro = '''
                    welcome to stack manage
p(U)sh
P(O)p
(V)iew
(Q)uit
Enter choice:'''
     while True:
         choice = raw_input(pro).lower()
         if choice =="u":
                  pushstack()
         elif choice == "o":
                  popstack()
         elif  choice == "v":
                  viewstack()
         elif  choice == "q":
                  print "quit stack manage"
                  break
         else:
                  print "input u,o,v,q"
showmenu()


__author__ = "lvah"
list1 = [1,2,3,4,1,2,3]
sl = set (list1)
print sl
s2 = {1,2,100,'hello'}



print sl.union(s2)
print sl.intersection(s2)
s2.intersection_update(sl)
print sl
print s2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值