zoukankan      html  css  js  c++  java
  • day 7 字符串

        

    6.字符串的常见操作
    知道方向,不要去背
      1)find,index                   #查找
     2)count 和replace               #替换
     3)split                         # 分割(数据清洗)
     4)capitalize 和 title           #首字母大写
      5)startswitch endswitch         #开头结尾(上传文件名称盘判断)
      6)lower,upper                  #转换为大小写(用户输入同一格式)
      7)center ,ljust,rjust           # 居中显示(网易云歌词)
     8)strip 去除空格,
    ,	            #(数据清洗)
      9) partition,rpartition           #分割 (广播体操带队)
     10)splitlines                    # 按行
    分割
      11) isdigit isalpha  isalnum     # 注册时,必须是字母和数字的组合
     12)join                          #构建字符串
      13)format:                   #格式化输出
    浮点数判断
    type(eval("123")) == int
    type(eval("123.23")) == float

    1.num=10 和 num=“10”的区别

      numb=10 内存中占用1个字节

      num=“10“ 内存中占用3个字节 

        

       注意:c语言中  字符串末尾还有结束符

        

    2.类型转换

    In [1]: num = 100
    
    In [2]: num2 = "100"
    
    In [3]: name = alex
    
    
    ######################
    
    In [5]: int(num2)
    Out[5]: 100
    
    In [6]: str(num)
    Out[6]: '100'
    
    ######################
    In [7]: len(name)
    Out[7]: 4               #在内存占用4个字节

            

    3.字符串拼接的2种方式

    In [9]: a = "lao"
    
    In [10]: b = "wang"
    
    In [11]: c = a+b
    
    In [12]: c
    Out[12]: 'laowang'
    
    In [13]: 
    
    ########################
    In [13]: A = 10
    
    In [14]: B = 2
    
    In [15]: C = A+B
    
    In [16]: C
    Out[16]: 12
    完成结果显示
    In [18]: "===langwang==="
    Out[18]: '===langwang==='
    
    #######################             第1种方式 
    
    In [19]: e = "===" + a + b + "==="
    
    In [20]: e
    Out[20]: '===laowang==='
    
    
    #######################             第2种方式
    In [21]: f = "===%s==="%(a+b)
    
    In [22]: f
    Out[22]: '===laowang==='

    4.字符串的下标

    In [23]: name = "abcdef"   
    
    In [24]: name[0]           #0 下标
    Out[24]: 'a'         #a  元素
    
    In [25]: name[5]
    Out[25]: 'f'
    
    
    ########################  越界
    In [26]: name[6]
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-26-b480563304b2> in <module>()
    ----> 1 name[6]
    
    IndexError: string index out of range
    
    
    
    #################   [-3][-2][-1]
    In [29]: name[len(name)-1]
    Out[29]: 'f'
    
    In [30]: name[-1]
    Out[30]: 'f'
    
    In [31]: name[-2]
    Out[31]: 'e'
    
    In [32]: name[-3]
    Out[32]: 'd'

        

     5.切片

    ####   正向切片
    In [33]: name = "abcdefABCDEF"
                               02345678910
    
    In [35]: name[2:5]         #实质 [2:5)
    Out[35]: 'cde'
     
    In [36]: name[2:6]         #实质[2:6)   就是[2:5]
    Out[36]: 'cdef'
    
    
    
    ######   反向切片
    In [33]: name = "abcdefABCDEF"
                                      -5-4-3-2-1
                               012345
    
    In [37]: name[2:-2]          #[2:              cdefgABCDEF
    Out[37]: 'cdefABCD'          #   :-2)        abcdefgABCD 
                                  #结果             cdefgABCD
     
    
    In [38]: name[2:-1]
    Out[38]: 'cdefABCDE'
    
    
    In [39]: name[2:-2]
    Out[39]: 'cdefABCD'
    
    
    In [40]: name[2:0]
    Out[40]: ''
    
    
    In [41]: name[2:]             #注意!正序全部
    Out[41]: 'cdefABCDEF'
                                                                            

      2)实质:【起始位置:终止位置:步长】

         

    In [42]: name[2:-1]
    Out[42]: 'cdefABCDE'
    
    In [43]: name[2:-1:2]
    Out[43]: 'ceACE'
    
    
    In [44]: name[2:-1:1]
    Out[44]: 'cdefABCDE'
    
    
    In [45]: name[2:-1]             #默认步长为1
    Out[45]: 'cdefABCDE'

      3)字符串的逆序(倒序)?

    In [46]: name
    Out[46]: 'abcdefABCDEF'
    
    #######     正序
    In [47]: name[0:]
    Out[47]: 'abcdefABCDEF'
    
    In [48]: name[-1:]
    Out[48]: 'F'
    
    In [49]: name[-1:0]
    Out[49]: ''
    
    ##########  倒序  (面试必考)
    
    In [50]: name[-1:0:-1]
    Out[50]: 'FEDCBAfedcb'
    
    In [51]: name[-1::-1]
    Out[51]: 'FEDCBAfedcba'
    
    In [52]: name[::-1]
    Out[52]: 'FEDCBAfedcba'

    6.字符串的常见操作

        知道方向,不要去背

      

    In [57]: my_str = "hello world python adn pythonxxxxcpp"
    
    In [59]: my_str.
    my_str.capitalize    my_str.isalnum       my_str.join          my_str.rsplit
    my_str.casefold      my_str.isalpha       my_str.ljust         my_str.rstrip
    my_str.center        my_str.isdecimal     my_str.lower         my_str.split
    my_str.count         my_str.isdigit       my_str.lstrip        my_str.splitlines
    my_str.encode        my_str.isidentifier  my_str.maketrans     my_str.startswith
    my_str.endswith      my_str.islower       my_str.partition     my_str.strip
    my_str.expandtabs    my_str.isnumeric     my_str.replace       my_str.swapcase
    my_str.find          my_str.isprintable   my_str.rfind         my_str.title
    my_str.format        my_str.isspace       my_str.rindex        my_str.translate
    my_str.format_map    my_str.istitle       my_str.rjust         my_str.upper
    my_str.index         my_str.isupper       my_str.rpartition    my_str.zfill

       

      1)find,index查找

    ##########   find
    In [60]: my_str.find("world")
    Out[60]: 6                #w的下标
    
    
    In [63]: my_str.find("python")   #从左边开始find
    Out[63]: 12
    
    In [64]: my_str.rfind("python")   #从右边开始find
    Out[64]: 23
    
    
    In [61]: my_str.find("redhat")      #没有find out 返回-1
    Out[61]: -1 
    
    
    ############# index
    In [67]: my_str.index("python")
    Out[67]: 12
    
    In [68]: my_str.rindex("python")
    Out[68]: 23
    
    
    In [66]: my_str.index("redhat")   
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-66-44374e6cd47d> in <module>()
    ----> 1 my_str.index("redhat")
    
    ValueError: substring not found                #没有找出返回异常

      2)count 和replace

     my_str = "hello world python adn pythonxxxxcpp"
    
    #########   count
    In [69]: my_str.count("python")
    Out[69]: 2
    
    In [70]: my_str.count("world")
    Out[70]: 1
    
    In [71]: my_str.count("rehdat")
    Out[71]: 0
    
    
    #########    replace
    
    In [72]: my_str.replace("world","WORLD")
    Out[72]: 'hello WORLD python adn pythonxxxxcpp'
    
    
    In [75]: my_str.replace("python","redhat",1)         #替换第1个
    Out[75]: 'hello world redhat adn pythonxxxxcpp'
    
    In [88]: my_str
    Out[88]: 'hello world python adn pythonxxxxcpp'
    
         #数字,字符串,元组   不可变类型

      3)split 分割(数据清洗)

    In [81]: my_str.split(" ")
    Out[81]: ['hello', 'world', 'python', 'adn', 'pythonxxxxcpp']  #返回list

      

      4)capitalize 和 title   首字母大写

    In [82]: my_str.capitalize()
    Out[82]: 'Hello world python adn pythonxxxxcpp'
    
    In [83]: 
    
    In [83]: my_str.title()
    Out[83]: 'Hello World Python Adn Pythonxxxxcpp'

      5)startswitch endswitch  开头结尾(上传文件名称盘判断)

    #上传文件名称的判断 
    
    In [93]: file_name
    Out[93]: 'redhat.txt'
    
    
    In [94]: file_name.endswith(".txt")
    Out[94]: True
    
    
    In [95]: file_name.startswith("redhat")
    Out[95]: True
    
     
    #  对文件内容的审查,模块    上传病毒

       

      6)lower,upper 转换为大小写(用户输入同一格式)

    In [97]: if choic == "yes":
       ....:     print("exit")
    
       ....: elif choice == "YES":
       ....:     print("exit")
       ....: elif ..
    
    
    #######   统一一种格式
    
    In [100]: choice = "Yes"
    
    In [101]: choice.lower()
    Out[101]: 'yes'
    
    In [102]: choice.upper()
    Out[102]: 'YES'

      

      7)center ,ljust,rjust  居中显示(网易云歌词)

          

    In [105]: lyric = "想要陪你一起看大海"
    
    In [106]: lyric.center(50)
    Out[106]: '                    想要陪你一起看大海                     '
    
    In [108]: lyric.ljust(50)
    Out[108]: '想要陪你一起看大海                                         '
    
    In [107]: lyric.rjust(50)
    Out[107]: '                                         想要陪你一起看大海'
        

       8)strip 去除空格, , (数据清洗)

        

    In [110]: lyric
    Out[110]: '                    想要陪你一起看大海                     '
    
    
    In [111]: lyric.lstrip()          #去除左
    ,	
    Out[111]: '想要陪你一起看大海                     '
    
    In [112]: lyric.rstrip()            #去除右
    ,	
    Out[112]: '                    想要陪你一起看大海'
    
    
    In [113]: lyric.strip()
    Out[113]: '想要陪你一起看大海'

      9) partition,rpartition  分割 (广播体操带队)

    In [114]: my_str
    Out[114]: 'hello world python adn pythonxxxxcpp'
    
    In [115]: my_str.partition("python")
    Out[115]: ('hello world ', 'python', ' adn pythonxxxxcpp')
    
    
    In [117]: my_str.rpartition("python")
    Out[117]: ('hello world python adn ', 'python', 'xxxxcpp')

      10)splitlines  按行 分割

    In [118]: my_line = "hello
    world
    xx
    yy
    zz"
    
    In [119]: print(my_line)
    hello
    world
    xx
    yy
    zz
    
    
    In [120]: my_line.splitlines()
    Out[120]: ['hello', 'world', 'xx', 'yy', 'zz']

      

      11) isdigit isalpha   isalnum  注册时,必须是字母和数字的组合

    s为字符串
    s.isalnum() 所有字符都是数字或者字母
    s.isalpha() 所有字符都是字母
    s.isdigit() 所有字符都是数字
    s.islower() 所有字符都是小写
    s.isupper() 所有字符都是大写
    s.istitle() 所有单词都是首字母大写,像标题
    s.isspace() 所有字符都是空白字符、	、
    、
    
    ###### 数字整数  isdigit
    In [12]: num = input("请输入一个选项:")
    请输入一个选项:1
    
    In [13]: if num.isdigit():
        int(num)
        print("是数字:",num)
       ....:     
    是数字: 1
    
    
    ######   字母 isalpha
    In [8]: num = input("请输入一个选项:")
    请输入一个选项:q
    
    In [9]: if num.isalpha():
        print("是字母")
        print(num)
       ...:     
    是字母
    q
    
    
    
    ##### 注册页面,必须是数字和字母的组合
    In [16]: num = "1q"
    
    In [17]: num.isdigit()
    Out[17]: False
    
    In [18]: num.isalpha()
    Out[18]: False
    
    
    In [20]: num.isalnum()          #alpha
    Out[20]: True                            #number
    
    
    #######   数字字母组合
    In [14]: num = input("请输入一个选项:")
    请输入一个选项:1q
    
    In [15]: if num.isalnum():
       ....:     print("是字母和数字",num)
       ....:     
    是字母和数字 1q

      12)join  构建字符串

    In [21]: a = ["aa","bb","cc"]
    In [22]: a
    Out[22]: ['aa', 'bb', 'cc']
    
    
    
    In [23]: b = "="
    
    In [24]: b.join(a)
    Out[24]: 'aa=bb=cc'
    
    
    
    In [25]: b = " "
    
    In [26]: b.join(a)
    Out[26]: 'aa bb cc'

      13)format:格式化输出

    # 格式化输出1
    >>> s = 'myname is {0}, i am {1}'
    >>>
    >>> s.format('alxe',22)
    'myname is alxe, i am 22'
    
    # 格式化输出2
    >>> s = 'myname is {name}, i am {age}'
    
    >>> s.format('alxe',22)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'name'
    >>>
    >>> s.format(name='alex',age=22)
    'myname is alex, i am 22'

      

    7.面试题:给定一个字符串Str,  去除所有的  空格和' ',返回字符串

    • (面试题)给定一个字符串Str,  去除所有的  空格和' ',返回字符串

        

    ####### 题目
    In [27]: test_str = "hello world nihao 	 heihie 	 woshi nide	python 
     ll
    du"
    
    
    ######  错误做法
    In [30]: test_str.split(" ")
    Out[30]: 
    ['hello',
     'world',
     'nihao',
     '	',
     'heihie',
     '	',
     'woshi',
     'nide	python',
     '
    ',
     'll
    du']
    
    
    In [32]: test_str.splitlines()
    Out[32]: ['hello world nihao 	 heihie 	 woshi nide	python ', ' ll', 'du']
    
    In [33]: test_str.split("	")
    Out[33]: ['hello world nihao ', ' heihie ', ' woshi nide', 'python 
     ll
    du']
    
    
    In [34]: test_str.split("
    ")
    Out[34]: ['hello world nihao 	 heihie 	 woshi nide	python ', ' ll', 'du']
    
    In [35]: test_str.split("	
    ")
    Out[35]: ['hello world nihao 	 heihie 	 woshi nide	python 
     ll
    du']
    
    
    
    #####  正确做法
    In [36]: test_str.split()
    Out[36]: ['hello', 'world', 'nihao', 'heihie', 'woshi', 'nide', 'python', 'll', 'du']
    #######  字符串拼接
    
    In [37]: result = test_str.split()
    
    In [39]: " ".join(result)
    Out[39]: 'hello world nihao heihie woshi nide python ll du'
    
    In [38]: "".join(result)
    Out[38]: 'helloworldnihaoheihiewoshinidepythonlldu'
  • 相关阅读:
    Python 解LeetCode:Intersection of Two Arrays
    flask中使用xlsxwriter导出excel文件
    python的xlwt模块的常用方法
    线程池理解
    内存屏障理解
    中断上半部,下半部理解
    DPDK l2fwd源码学习
    如何用perf工具
    如何迅速分析出系统CPU的瓶颈在哪里?
    怎么理解Linux软中断?
  • 原文地址:https://www.cnblogs.com/venicid/p/7843602.html
Copyright © 2011-2022 走看看