Python core Programming chapter sixth Exercise 6-12

Source: Internet
Author: User

6-12.
String.
(a) Create a function with the name FINDCHR (), which is declared below.
Def findchr (String, char)
FINDCHR () to look up the character char in string strings, find it to return the worthy index, otherwise return-1. You cannot use String.*find () or String.*index () functions and methods.
(b) Create another function called RFINDCHR () to find the last occurrence of the character char. It works like FINDCHR (), but it looks forward from the end of the string.
(c) Create a third function, called SUBCHR (), declared as follows.
Def subchr (String, Origchar, Newchar)
SUBCHR () is similar to FINDCHR (), but the difference is that if a matching character is found, the original character is replaced with a new character. Returns the modified string.
Answer
(a) The code is as follows:
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 being find in this string ... ‘)
FINDCHR (A, B)

(b) The code is as follows:
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 being find in this string ... ‘)
RFINDCHR (A, B)

(c) The code is as follows:
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 ')

The above originates from:

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

Python core Programming chapter sixth Exercise 6-12

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.