0

I want to expand "Dr." into either "Doctor" or "Drive" to clear the confusion.

string = 'Dr. Seuss Dr.'
if string[0:3] == "Dr.":
    new_string = 'Doctor Seuss Dr.'
if string[:3] == "Dr.":
    another_string = 'Dr. Seuss Drive'

Is there a better way to expand out "Dr."? I can't handle cases if the string is 'I like Dr. Seuss'!

2
  • 2
    What is your question? Commented Mar 3, 2013 at 7:16
  • Is this for a toy program/exercise, or for real-world use? Commented Mar 3, 2013 at 7:42

2 Answers 2

4

Something like this?

mystring = 'Dr. Seuss Dr.'
if 'Dr.' in mystring:
    mystring = mystring.replace('Dr.', 'Doctor', 1).replace('Dr.', 'Drive')

The first replace only replaces Dr. once (notice the extra parameter added).

Thanks to shantanoo for pointing out that there is a module string and so variable names should avoid such word. I have changed the variable to mystring.

Sign up to request clarification or add additional context in comments.

6 Comments

+1 It's easy to forget that .replace takes a count parameter
But that would expand "Manor Dr." to "Manor Doctor", wouldn't it?
@NPE Well the question isn't clear. How do we know what is Doctor and what is Drive? I don't think the OP was intending to imply that the position in the string mattered, and maybe that his use of string slicing was the only method he/she could think of.
@Haidro: I agree that the question is not entirely clear. However, it seems reasonably clear that, for example, 'Doctor Seuss Dr.' should expand to 'Doctor Seuss Drive' and not to 'Doctor Seuss Doctor'.
string is the python module. Its better not to use it as variable.
|
1

I guess that you want to convert Dr. into Doctor if it is at the beginning of the string. Otherwise, you want Dr. to be converted into Driver.

You can use regex to achieve this:

import re
string = 'Dr. Seuss Dr.'
string = re.sub(re.compile('^Dr.'), 'Doctor', string)
string = re.sub(re.compile('Dr.$'), 'Driver', string)
#now string contains 'Dr. Seuss Drive'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.