zoukankan      html  css  js  c++  java
  • 0509---字符串练习题

    #6、字符替换
    '''
    1)读入一个字符串
    2)去掉字符串的前后空格
    3)如果字符串包含数字则1替换成a,2替换成b,3替换成c,以此类推
    4)将字符串使用空格进行切分,存到一个列表,然后使用*号连接,并输出
    5)把这些功能封装到一个函数里面,把执行结果作为返回值
    '''

    def replace_str(s):
        if not isinstance(s,str):
            return None
        s=list(s.strip())#strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
        print(s)
        result =[]
        for i in s:
            if i.isdigit():
                result.append(chr(ord(i)+48))
            else:
                result.append(i)
        return "*".join(result)
    
    s = "  123456789abc "
    print(replace_str(s))

    C:UsersAdministrator>py -3 C:UsersAdministratorDesktop测试python相关20190423
    .py
    ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c']
    a*b*c*d*e*f*g*h*i*a*b*c

    #7、找出字符串中出现次数最多的字符,并输出其出现的位置

    s="I am a good boy!"
    def max_times_num_str(s):
    
        import string
        for i in s:
            if i in string.punctuation:
                s=s.replace(i," ")
        s=s.split()
        d={}
        for i in range(len(s)):
            for j in range(len(s[i])):
                if s[i][j] not in d.keys():
                    d[s[i][j]] =1
                else:
                    d[s[i][j]] +=1
        max_num=max(d.values())
        for k,v in d.items():
            if v==max_num:
                return (k,v)
    
    
    print(max_times_num_str(s))

    C:UsersAdministrator>py -3 C:UsersAdministratorDesktop测试python相关20190423
    .py
    ('o', 3)

     方法2:如果有多个相同的最大值,貌似就找不出来了。

    #算法:定义一个出现次数最多的字符的坐标位置为0 

    2 按坐标遍历后,用count找到出现次数最多的字符,替换坐标位置,然后返回

    def find_max(s):
        max_num_index =0
        for i in range(len(s)):
    #用坐标取
    if s.count(s[i]) >s.count(s[max_num_index]): max_num_index=i return s[max_num_index],max_num_index print(find_max("hewhewkhkewjkwjkjjkjkjk"))

    C:UsersAdministrator>py -3 C:UsersAdministratorDesktop测试python相关20190423
    .py
    ('k', 6)

    #8、找出一段句子中最长的单词及其索引位置,以字典返回字符串的练习题

    #enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

    import string
    def max_length_word(s):
        s=s.split(" ")
        d={}
        for index,i in enumerate(s):
            print(i)#enumerate输出的是一个索引序列
            d[len(i)]=(i,index)#长度作为字典的key,i和index作为一个组赋值给value
            print(d)
        return d[max(d.keys())]
    
    s='I am a good boy'
    print(max_length_word(s))

    C:Usersdell>py -3 C:UsersdellDesktop练习5509.py
    I
    {1: ('I', 0)}
    am
    {1: ('I', 0), 2: ('am', 1)}
    a
    {1: ('a', 2), 2: ('am', 1)}
    good
    {1: ('a', 2), 2: ('am', 1), 4: ('good', 3)}
    boy
    {1: ('a', 2), 2: ('am', 1), 4: ('good', 3), 3: ('boy', 4)}
    ('good', 3)

    对比题:

    #81、找出一段句子中最长的单词及其索引位置,以list返回
    import re
     
    word_str = input("请输入一个英文句子:")
    def find_max_length(word_str):
        word = sorted(re.findall(r'w+',word_str),key=len)[-1]
        postion = 0
        for index in range(len(word_str)):
            if word_str[index:index+len(word)] == word:
                postion = index
                break
        return word,postion
     
    print("句子中最长的单词是%s,索引位置是%d" %(word,postion))

    #10、实现字符串的upper、lower以及swapcase方法

    #pper() 方法将字符串中的小写字母转为大写字母
    s="Hgdj"
    ''' 
    def upper(s):
        if not isinstance(s,str):
            return None
        result =""
        for i in s:
            if i>='a' and i<='z':
                result +=chr(ord(i)-32)
            else:
                result +=i
        return result
    
    print(upper(s))
    '''
    #lower() 方法转换字符串中所有大写字符为小写。
    '''
    def lower(s):
        if not isinstance(s,str):
            return None
        result =""
        for i in s:
            if i>='A' and i<='Z':
                result +=chr(ord(i)+32)
            else:
                result +=i
        return result
    
    print(lower(s))
    '''
    #swapcase() 方法用于对字符串的大小写字母进行转换。
    def swapcase(s):
        if not isinstance(s,str):
            return None
        result =""
        for i in s:
            if i>='a' and i<='z':
                result +=chr(ord(i)-32)
            else:
                result +=chr(ord(i)+32)
        return result
    
    print(swapcase(s))
    C:Usersdell>py -3 C:UsersdellDesktop练习5509.py
    HGDJ
    C:Usersdell>py -3 C:UsersdellDesktop练习5509.py
    hgdj
    C:Usersdell>py -3 C:UsersdellDesktop练习5509.py
    hGDJ
     
    >>> s="THIS is string example....wow!!!"
    >>> print(s.swapcase())
    this IS STRING EXAMPLE....WOW!!! 
     
     
     
    #11、实现字符串的find方法
    find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内
    >>> info ='abca'
    >>> print(info.find('a')) # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
    0
    >>> print(info.find('a',1))   # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3
    3
    >>> print(info.find('3')) # 查找不到返回-1
    -1
    >>> 
     
    #算法:检测字符串中是否包含子字符串,如果存在返回索引值在字符串中的起始位置,如果不包含索引值,返回-1
    def find(s,word,num=0):
        if not isinstance(s,str):
            return None
        if word in s:
            for i in range(len(s)):
                if s[i:i+len(word)]==word:
                    return i
        else:
                return -1
                
    print(find('good','d'))
    print(find('is good boy','boy'))

    C:Usersdell>py -3 C:UsersdellDesktop练习5509.py
    3
    8

     
  • 相关阅读:
    slim的中间件
    slim中的请求头
    slim中的参数获取
    redis的事务操作
    关于redis有序集合http://www.runoob.com/redis/redis-sorted-sets.html
    linux下的一些命令的笔记
    slim的简单使用
    在windows+nginx的curl操作请求超时的问题
    关于启动php-fpm失败的解决办法
    lintcode-【中等】恢复IP地址
  • 原文地址:https://www.cnblogs.com/wenm1128/p/10839858.html
Copyright © 2011-2022 走看看