zoukankan      html  css  js  c++  java
  • Python--数据类型之一 数字(Number)和String(字符串)


    1、pycharm使用前的一些简单设置

     1、注释模板设置

      为了不由每次新建一个py文件都输入下面注释可如图设置:

    #!/usr/bin/env/python
    # _*_coding:utf-8 _*_

     具体设置为: 打开file->settings->Editor->file and code template->python script,然后在模板内输入上面两行代码保存即可.

      

     2、文字大小和颜色和风格

      打开file->settings->Editor->Colors & Fonts
      file-settings-appearance-theme-选择自己需要的风格
      先单击save as,然后在size里面输入适合的大小,根据自身需要设置

      

    2、 基本数据类型

     1、六个标准的数据类型:

    • Numbers(数字)
    • String(字符串)
    • List(列表)
    • Tuple(元组)
    • Sets(集合)
    • Dictionaries(字典)

     2、Numbers(数字

      Python 支持三种不同的数值类型:整型(int)、浮点型(float)、复数(complex)

      复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型

      python数字类型相互转换
      int(x) 将x转换为一个整数。
      float(x) 将x转换到一个浮点数。

      complex(x) 将x转换到一个复数,实数部分为 x,虚数部分为 0。complex(x, y) 将 x 和 y 转换到一个复数,实数部分为 x,虚数部分为 y。x 和 y 是数字表达式。

      我们可以用type来判断当前数据类型

    >> a =222
    >>> b =21.3443
    >>> print(type(a))
    <class 'int'>
    >>> print(type(b))
    <class 'float'>
    >>> 

      
     3、String(字符串)
      字符串表示非常简单,一对双引号即可

    str1 = "Hello world"
    str2 = "I love python"

      字符串本质上就是由多个字符组成的,因此程序允许通过索引来操作字符

      1、首先我们可以通过print打印出字符串,再通过type查看它的数据类型,

    str1 = "Hello world"
    str2 = "I love python"
    print(str1)
    print(type(str1))
    print(str2)
    print(type(str2))
    结果:
    Hello world
    <class 'str'>
    I love python
    <class 'str'>

       2、访问字符串中的值和分片

    str1 = "Helloworld"
    str2 = "Ilovepython"
    
    print("str1[0]:",str1[0])#得到第一个字母
    print("str2[3:6]:",str2[3:6])#得到第三到六的字母
    str = "string"
    str[1:3] # "tr",获取从偏移为1到偏移为3的字符串,不包括偏移为3的字符
    str[1:] # "tring"获取从偏移为1到最后的一个字符,不包括最后一个字符
    str[:3] #"str"获取从偏移为0的字符一直到偏移为3的字符串,不包括偏移为3的字符串
    str[:-1] #strin"获取从偏移为0的字符一直到最后一个字符(不包括最后一个字符串)     
    str[:] #"string"获取字符串从开始到结尾的所有元素   
    str[-3:-1] #"in"获取偏移为-3到偏移为-1的字符,不包括偏移为-1的字符 
    str[::-1] # "gnirts"反转输出

      3、字符串的方法

       replace()方法replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次

        str = "This is A Test"
        print(str.replace("is", "was"))  # Thwas was A Test"
        print(str.replace("is", "was", 1)) #Thwas is A Test

      find()方法find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1

    str.find(str,beg = 0, end = len(str))

      str -- 指定检索的字符串
      beg -- 开始索引,默认为0。
      end -- 结束索引,默认为字符串的长度。
      返回值: 如果包含子字符串返回开始的索引值,否则返回-1

    str1 = "python web: www.python.org"
    str2 = "we"
    print(str1.find(str2)) # 7
    print(str1.find(str2, 3)) # 7
    print(str1.find(str2, 8)) # -1
  • 相关阅读:
    SCCM2012 R2实战系列之七:软件分发(exe)
    man 手册--nc
    挂载虚拟机磁盘文件
    bond模式详解
    Windows下计算md5值
    man手册--iostat
    mount---挂载文件系统
    Linux-swap分区
    sync---强制将被改变的内容立刻写入磁盘
    vmstat---有关进程、虚存、页面交换空间及 CPU信息
  • 原文地址:https://www.cnblogs.com/ncne/p/10924660.html
Copyright © 2011-2022 走看看