linuxoverdose
linuxoverdose

Reputation: 11

google python class string1 exercise

I working on the string1 exercise that is a part of the Google Python class. The question I'm having problems with is C:

C. fix_start
Given a string s, return a string
where all occurences of its first char have
been changed to '*', except do not change
the first char itself.
e.g. 'babble' yields 'ba**le'
Assume that the string is length 1 or more.
Hint: s.replace(stra, strb) returns a version of string s
where all instances of stra have been replaced by strb.

I was thinking of use a loop to compare each letter with the first letter and replace any that match with '*'. I think there has to be an easier way though. Does anyone have any suggestions?

Upvotes: 1

Views: 3813

Answers (4)

bmordan
bmordan

Reputation: 11

Here is my longer solution. I broke the s up into 2 parts and worked the replace on the second part of the string the 'rest' of the word. It is longer but included here to show a thought process to solve the puzzle.

def fix_start(s):
  star = s[0]
  rest = s[1:]
  rest = rest.replace(star,'*')

  return star+rest

Upvotes: 1

Delecron
Delecron

Reputation: 119

Here is what I got, no loop required.

def fix_start(s):

  return s[0]+s[1:].replace(s[0], '*')

This only works considering they tell us we should assume the string is not ''. In that case the return line should be moved to the body into an if and the len checked first.

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208495

There is already a hint provided, and it does not involve using a loop!

It suggests using s.replace(stra, strb) and describes what effect that would have, so given the problem statement lets look at what s, stra, and strb should be.

  • We only want to replace occurrences after the first character, so the s in s.replace(stra, strb) should be everything from the second character on. We can get this using the slice s[1:] (here s is the parameter passed into the function).
  • Since we want to replace all occurrences of the first character, stra should be that first character, or s[0] (again s is the parameter).
  • strb is easy, it says we are replacing the matches with *, so strb is '*'

So somewhere in your function, you will want s[1:].replace(s[0], '*'), that will get you most of the way there.

Upvotes: 1

NPE
NPE

Reputation: 500427

Yes, there is an easier way to do it, and the question already gives you a hint:

s.replace(stra, strb) returns a version of string where all instances of stra have been replaced by strb.

Think about how you might use that function.

Upvotes: 1

Related Questions