zoukankan      html  css  js  c++  java
  • python基础二——list与字符串

    1.使用命令行编译python文件

    打开命令行,切换盘符,切换到python安装目录。随便找个文本软件写代码,保存为py文件。使用命令 “python 文件名”  实现编译。

    用命令"exit()"退出python

    2.list学习

    from random import choice
    print 'Choose one side to shoot:'
    print 'left,center,right'
    you=raw_input()          #无论输入什么,都转化为字符串形式
    print'You kicked '+you
    direction=['left','center','right']
    com=choice(direction)             #choice函数是从list中随便选出一个值
    print 'Computer saved'+com
    if you!=com:
        print'Goal!'
    else:
        print 'Ooops...'
    print direction[0]   #访问list中的元素
    direction[0]='up'    #修改
    direction.append(1024)  #增加
    del direction[0]     #删除
    direction=['left','center','right','up']
    direction[-1]   #list中的最后一个元素
    direction[-3]   #list中的倒数第三个元素
    direction[1:3]  #结果是['center','right']
    direction[1:-1] #结果是['center','right']

    3.分割字符串

    sentence="I'm a student"
    list=sentence.split()
    print list
    
    sentence="Hi. I am the one. Bye."
    list=sentence.split('.')               #按'.'分割
    print list
    
    sentence="Hi. I am the one. Bye"
    list=sentence.split('.')
    print list
    
    print 'aaa'.split('a')

    结果:

    >>>
    ["I'm", 'a', 'student']
    ['Hi', ' I am the one', ' Bye', '']
    ['Hi', ' I am the one', ' Bye']
    ['', '', '', '']
    >>>

    4.联合字符串

     join是一个字符串的方法,而不是list的方法,该字符串可以是空字符串

    >>> ''.join(['hello','world'])
    'helloworld'
    >>> s=";"
    >>> fruits=s.join(['apple','orange'])
    >>> print fruits
    apple;orange

    5.字符串的索引和切片

    (1)可以用for...in...来遍历

    (2)类似于list可以通过索引方式查看

    (3)不同于list的是不能够通过索引来赋值

    (4)可以切片

    (5)可以连接字符

    >>> for c in word:
        print c,
    
        
    h e l l o w o r d
    >>> word[0]
    'h'
    >>> word[0]='g'
    
    Traceback (most recent call last):
      File "<pyshell#14>", line 1, in <module>
        word[0]='g'
    TypeError: 'str' object does not support item assignment
    >>> print word[5:7]
    wo
    >>> word[:]
    'helloword'
    >>> ','.join(word)
    'h,e,l,l,o,w,o,r,d'
    >>> 

    6.打印文件

    >>> dirname='C:UsersdellDesktop'
    >>> f=file(dirname+'新建文本文档.txt')        #打开文件
    >>> data=f.read()              #阅读文件内容到data中
    >>> data1=f.readline()    #打印一行内容到data1中
    >>> data2=f.readlines()   #打印内容到list中
    >>> print data               #打印内容
    >>> f.close()

    7.修改文件

    >>> f=file(dirname+'新建文本文档.txt','w')   #注意会清空原有文件

    8.练习文件处理

  • 相关阅读:
    虚拟机设置与主机同网段的IP
    centos8 安装docker
    postgresql10 修改密码及远程访问
    centos7 安装pycharm
    centos7安装Python
    docker容器固定ip
    centos7 redis 自启动
    centos7 nginx添加自启
    docker 容器时间不正确的修改方法
    浅谈麦克斯韦方程组与相对论
  • 原文地址:https://www.cnblogs.com/wy1290939507/p/4745045.html
Copyright © 2011-2022 走看看