zoukankan      html  css  js  c++  java
  • python核心编程第六章练习6-12

    6-12.
    字符串。
    (a)创建一个名字为findchr()的函数,函数声明如下。
    def findchr(string, char)
    findchr()要在字符串string中查找字符char,找到就返回该值得索引,否则返回-1。不能用string.*find()或者string.*index()函数和方法。
    (b)创建另一个叫rfindchr()的函数,查找字符char最后一次出现的位置。它跟findchr()工作类似,不过它是从字符串的最后开始向前查找的。
    (c)创建第三个函数,名字叫subchr(),声明如下。
    def subchr(string, origchar, newchar)
    subchr()跟findchr()类似,不同的是,如果找到匹配的字符就用新的字符替换原先字符。返回修改后的字符串。
    【答案】
    (a)代码如下:
    def findchr(string, char):
        a = string
        k = index = -1
        for i in a:
            k = k + 1
            if i == char: 
                index = k
                print index
        if index == -1: print 'index = ', index
        
    a = raw_input('Please input a string ... ')
    b = raw_input('Please input a character to be find in this string ... ')
    findchr(a, b)        
            
    (b)代码如下:
    def rfindchr(string, char):
        a = string
        k = index = -1
        for i in a:
            k = k + 1
            if i == char: 
                index = k
        print index
        if index == -1: print 'index = ', index
        
    a = raw_input('Please input a string ... ')
    b = raw_input('Please input a character to be find in this string ... ')
    rfindchr(a, b) 

    (c)代码如下:
    def subchr(string, origchar, newchar):
        output = ''
        for i in origchar:
            if i == string:
                output = output + newchar
            else:
                output = output + i
        print output
                
    subchr('c', 'abcddfasdfddacda', 'k')    

    以上源自:

    http://www.cnblogs.com/balian/archive/2011/05/31/2064213.html

  • 相关阅读:
    LeetCode-165 Compare Version Numbers
    shop--6.店铺注册--Thumbnailator图片处理和封装Util
    shop--6.店铺注册
    shop--5.使用Junit进行验证
    shop--4.SSM的各项配置
    shop--3.配置Maven
    shop--2.项目设计和框架搭建
    shop--1.创建maven项目
    AJAX 使用FormData 传送数据 DATA 为空 现象的处理
    Daemon Thread [http-nio-8080-exec-5] (Suspended (exception UnsatisfiedDependency))
  • 原文地址:https://www.cnblogs.com/Kaivenblog/p/4636050.html
Copyright © 2011-2022 走看看