• Python字符串处理和输入输出


    Python写一些字符串模拟题还是方便挺多,稍微整理一下,以免遗忘

    切片操作

    1.简单切片

    前闭后开,字符串下标从0开始
     s[ start : stop ] 
     s[:a] ->表示开头截取到某个特定的位置
     s[a:] ->某一位开始截取到最后一位可以用
     索引为为负数:从-1开始,表示最后一位
    

    2.带步长切片

    s [start: stop: stride]
    当步长为负数,反方向的截取部分的字符串,步长的绝对值大于1表示间隔的取数。
    例如:s[::-1],表示反转字符串。
    	  前两个参数省略,表示从开头到结尾,负号表示从右到左,1表示步长。
    

    3.练习

    import numpy as np
    a=np.random.rand(5)
    print(a)
    [ 0.64061262  0.8451399   0.965673    0.89256687  0.48518743]
     
    print(a[-1]) ###取最后一个元素
    [0.48518743]
     
    print(a[:-1])  ### 除了最后一个取全部
    [ 0.64061262  0.8451399   0.965673    0.89256687]
     
    print(a[::-1]) ### 取从后向前(相反)的元素
    [ 0.48518743  0.89256687  0.965673    0.8451399   0.64061262]
     
    print(a[2::-1]) ### 取从下标为2的元素翻转读取
    [ 0.965673  0.8451399   0.64061262]
    

    字符串运算符

    + : 字符串连接
    * :	重复输出字符串,a*2 输出结果:HelloHello
    in : 	 'H' in a 输出结果 True
    not in : 'M' not in a 输出结果 True
    

    常见字符串函数

    	
    count(str, beg= 0,end=len(string))
    # 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
    	
    find(str, beg=0, end=len(string))
    #检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1
    
    join(seq)
    str = "-";
    seq = ("a", "b", "c"); # 字符串序列
    print str.join( seq );
    # 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
    	
    len(string)
    # 返回字符串长度	
    lower()
    # 转换字符串中所有大写字符为小写.
    split(str="", num=string.count(str))
    # num=string.count(str)) ,以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串
    

    输入输出

    多组输入,每一组输入两个int

    try:
      while True:
        a, b= map(int, input().split())
        print(a+b)
    except EOFError:
        pass
    
    while True:
        a, b= map(int, input().split())
        if a==0 and b==0 :
            break
        print(a+b)
    
  • 相关阅读:
    leetcode 18 4Sum
    leetcode 71 Simplify Path
    leetcode 10 Regular Expression Matching
    leetcode 30 Substring with Concatenation of All Words
    leetcode 355 Design Twitte
    leetcode LRU Cache
    leetcode 3Sum
    leetcode Letter Combinations of a Phone Number
    leetcode Remove Nth Node From End of List
    leetcode Valid Parentheses
  • 原文地址:https://www.cnblogs.com/gzr2018/p/13226371.html
Copyright © 2020-2023  润新知