zoukankan      html  css  js  c++  java
  • Python正课18 —— 基本数据类型

    本文内容皆为作者原创,如需转载,请注明出处:https://www.cnblogs.com/xuexianqi/p/12456287.html

    一:定义

    msg = 'hello'   #本质:name = str('任意形式内容')
    

    二.类型转换

    数据类型转换:str()可以将任意数据类型转换成字符串类型,例如

    # msg = 'hello'   # msg = str('hello')
    # print(type(msg))
    
    <class 'str'>
    

    三:使用(内置方法)

    优先掌握:

    1.按索引取值

    正向取值

    msg = 'hello world'
    print(msg[0])
    print(msg[6])
    
    h
    w
    

    反向取值

    msg = 'hello world'
    print(msg[-1])
    
    d
    

    只能取,不能改

    msg[0] = 'H'	#会提示报错
    

    2.切片:索引的拓展应用,从一个大字符串中拷贝出一个子字符串

    顾头不顾尾

    msg='hello world'
    res=msg[1:7] #从下标1(也就是第2个字符)开始取,取到下标7-1(第7个字符),空格占1个字符串
    print(res)
    
    ello w
    

    步长

    msg='hello world'
    res=msg[0:5:2] # 从下标0(也就是第1个字符)开始取,取到下标6-1(第5个字符),步长为2
    print(res) 
    
    hlo
    

    反向步长(了解)

    msg='hello world'
    res=msg[5:0:-1]	# 从下标5(也就是第6个字符)开始取,取到下标0(第1个字符),步长为-1
    print(res)
    
     olle
    

    正常取值

    msg='hello world'
    res=msg[:] # 相当于res=msg[0:11]
    print(res)
    
    hello world
    

    反向取值

    msg='hello world'
    res=msg[::-1] # 把字符串倒过来
    print(res)
    
    dlrow olleh
    

    3.长度len

    msg='hello world'
    res = len(msg)	# len用于计算字符串的长度,输出的类型为str
    print(msg,type(msg))
    
    hello world <class 'str'>
    

    4.成员运算in和not in

    判断一个子字符串是否存在于一个大字符串中

    print("alex" in "alex is sb")
    
    True
    
    print("alex" not in "alex is sb")
    
    False
    
    print(not "alex" in "alex is sb") # 不推荐使用
    
    False
    

    5.移除字符串左右两侧的符号strip

    默认去掉的是空格

    msg='      egon      '
    res=msg.strip()
    print(msg) # 不会改变原值
    print(res) # 是产生了新值
    
          egon      
    egon
    

    可以去掉指定的字符

    msg='****egon****'
    print(msg.strip('*'))
    
    egon
    
    msg='**/*=-**egon**-=()**'
    print(msg.strip('*/-=()'))
    
    egon
    

    strip只去两边,不去中间(了解)

    msg='****e*****gon****'
    print(msg.strip('*'))
    
    e*****gon
    

    应用:

    inp_user=input('your name>>: ').strip() # inp_user=" egon"
    inp_pwd=input('your password>>: ').strip()
    if inp_user == 'egon' and inp_pwd == '123':
        print('登录成功')
    else:
        print('账号密码错误')
    

    6.切分split:把一个字符串按照某种分隔符进行切分,得到一个列表

    默认分隔符是空格

    info='egon 18 male'
    res=info.split()
    print(res)
    
    ['egon', '18', 'male']
    

    可以指定分隔符

    info='egon:18:male'
    res=info.split(':')
    print(res)
    
    ['egon', '18', 'male']
    

    可以指定分隔次数(了解)

    info='egon:18:male'
    res=info.split(':',0)	# 分隔次数为0,就是不分隔
    print(res)
    
    ['egon:18:male']
    
    info='egon:18:male'
    res=info.split(':',1)
    print(res)
    
    ['egon', '18:male']
    

    7.循环

    info='egon:18:male'
    for x in info:
        print(x)
        
    e
    g
    o
    n
    :
    1
    8
    :
    m
    a
    l
    e
    

    四:需要掌握

    1.strip、lstrip、rstrip

    strip:移除字符串中指定的符号

    msg='***egon****'
    print(msg.strip('*'))	# 可以移除字符串中指定的符号
    

    lstrip:移除字符串左侧指定的符号

    msg='***egon****'
    # print(msg.strip('*'))
    print(msg.lstrip('*'))
    
    egon****
    

    rstrip:移除字符串右侧指定的符号

    msg='***egon****'
    print(msg.rstrip('*'))
    
    ***egon
    

    2.lower、upper

    lower:把字符串中所有字母变成小写字母

    msg='AbbbCCCC'
    print(msg.lower())
    
    abbbcccc
    

    upper:把字符串中所有字母变成大写字母

    msg='AbbbCCCC'
    print(msg.upper())
    
    ABBBCCCC
    

    3.startswith、endswith

    startswith:用于判断一段字符串是否以某段字符或者某个字符串开头

    print("alex is sb".startswith("alex"))
    
    True
    

    endswith:用于判断一段字符串是否以某段字符或者某个字符串结尾

    print("alex is sb".endswith('sb'))
    
    True
    

    4.format:格式化输出

    其实就是format()后面的内容,填入大括号中(可以按位置,或者按变量)

    res='我的名字是 {} 我的年龄是 {}'.format('egon',18)
    print(res)
    
    我的名字是 egon 我的年龄是 18
    

    5.split、rsplit:将字符串切成列表

    split:从左往右切分

    info="egon:18:male"
    print(info.split(':',1))
    
    ['egon', '18:male']
    

    rsplit:从右往左切分

    info="egon:18:male"
    print(info.rsplit(':',1))
    
    ["egon:18","male"]
    

    6.join: 把列表拼接成字符串

    按照某个分隔符号,把元素全为字符串的列表拼接成一个大字符串

    l=['egon', '18', 'male']
    res=l[0]+":"+l[1]+":"+l[2]
    res=":".join(l) 
    print(res)
    
    egon:18:male
    

    7.replace:替换

    msg="you can you up no can no bb"
    print(msg.replace("you","YOU",))
    
    YOU can YOU up no can no bb
    

    可以自定义要替换几个

    msg="you can you up no can no bb"
    print(msg.replace("you","YOU",1))
    
    YOU can you up no can no bb
    

    8.isdigit:判断字符串是否由纯数字组成

    print('123'.isdigit())
    
    True
    
    print('12.3'.isdigit())
    
    False
    

    For example:

    age=input('请输入你的年龄:').strip()
    if age.isdigit():
        age=int(age) # int("abbab")
        if age > 18:
            print('猜大了')
        elif age < 18:
            print('猜小了')
        else:
            print('才最了')
    else:
        print('必须输入数字,傻子')
    

    五:了解即可

    1.find、rfind、index、rindex、count

    find:找到返回起始索引

    print(msg.find('e')) # 返回要查找的字符串在大字符串中的起始索引
    print(msg.find('egon'))
    
    1
    6
    

    index:

    print(msg.index('e'))
    print(msg.index('egon'))
    
    1
    6
    

    返回-1:

    print(msg.find('xxx')) # 返回-1,代表找不到
    
    -1
    

    index 抛出异常

    print(msg.index('xxx')) # 抛出异常
    
        print(msg.index('xxx')) # 抛出异常
    ValueError: substring not found
    

    count:计算字符串在大字符串中出现的次数

    msg='hello egon hahaha egon、 egon'
    print(msg.count('egon'))
    
    3
    

    2.center、ljust、rjust、zfill

    center:在center内容中间添加内容

    print('egon'.center(50,'*'))
    
    ***********************egon***********************
    

    ljust:在ljust内容左边添加内容

    print('egon'.ljust(50,'*'))
    
    egon**********************************************
    

    rjust:在ljust内容右边添加内容

    print('egon'.rjust(50,'*'))
    
    **********************************************egon
    

    zfill:在zfill内容中加到指定个数

    print('egon'.zfill(10))
    
    000000egon
    

    3.expandtabs

    设置制表符代表的空格数

    msg='hello	world'
    print(msg.expandtabs(2)) # 设置制表符代表的空格数为2
    
    hello world
    

    4.captalize、swapcase、title

    captalize:一段字符串的首个字母大写,其余小写

    print("hello world egon".capitalize())
    
    Hello world egon
    

    swapcase:一段字符串的首个字母小写,其余大写

    print("Hello WorLd EGon".swapcase())
    
    hELLO wORlD egON
    

    title:每个单词的首字母大写,其余小写

    print("hello world egon".title())
    
    Hello World Egon
    

    5.is系列

    .isdigit():判断是否全部都是纯数字类型

    print('123'.isdigit())
    
    True
    

    .islower():判断是否全部都是小写字母

    print('abc'.islower())
    
    True
    

    .isupper():判断是否全部都是大写字母

    print('ABC'.isupper())
    
    True
    

    .istitle():判断是否是单词首个字母大写

    print('Hello World'.istitle())
    
    True
    

    .isalnum():判断是否由数字或字母组成

    print('123123aadsf'.isalnum()) # 字符串由字母或数字组成结果为True
    
    True
    

    .isalpha():判断是否全部由字母构成

    print('ad'.isalpha()) # 字符串由由字母组成结果为True
    
    True
    

    .isspace():判断是否全部由空格构成

    print('     '.isspace()) # 字符串由空格组成结果为True
    
    True
    

    .isidentifier():判断是否可以定义为变量名

    print('print'.isidentifier())
    print('age_of_egon'.isidentifier())
    print('1age_of_egon'.isidentifier())
    
    True
    True
    False	# 变量名不能以数字开头
    

    6.数字系列的识别

    先定义表示同一个数字的4个不同方法:

    num1=b'4' #bytes
    num2=u'4' #unicode,python3中无需加u就是unicode
    num3='四' #中文数字
    num4='Ⅳ' #罗马数字
    

    isdigit只能识别:num1、num2

    print(num1.isdigit()) # True
    print(num2.isdigit()) # True
    print(num3.isdigit()) # False
    print(num4.isdigit()) # False
    
    True
    True
    False
    False
    

    isnumberic可以识别:num2、num3、num4

    print(num2.isnumeric()) # True
    print(num3.isnumeric()) # True
    print(num4.isnumeric()) # True
    
    True
    True
    True
    

    isdecimal只能识别:num2

    print(num2.isdecimal()) # True
    print(num3.isdecimal()) # False
    print(num4.isdecimal()) # False
    
    True
    False
    False
    
  • 相关阅读:
    Java基本数据类型
    Java入门
    JavaSE概述
    ORACLE中的自治事务
    JDWP Transport dt socket failed to initialize
    jinfo命令 Java Configuration Info
    mysql的bind-address设置为127 0 0 1,通过localhost连接访问不了
    与MQ通讯的完整JAVA程序
    Hadoop入门进阶步步高(三)-配置Hadoop
    GC Root
  • 原文地址:https://www.cnblogs.com/xuexianqi/p/12456287.html
Copyright © 2011-2022 走看看