5
>>> import string
>>> s = 'happy cat'
>>> string.find(s, 'cat')
6

and

>>> s = 'happy cat'
>>> s.find('cat')
6

In the above 2 pieces of code, i have the following doubts.

  1. Why is the 2nd code working without import the string module?
  2. Is there any performance improvement in using one over the other?

Thanks, Vinay

3
  • Why is the 1st piece of code working at all, is my question! Commented Jan 5, 2012 at 9:34
  • @wim: The first piece of code isn't working. It cannot work. It has to be string.find('happy cat', 'cat') Commented May 24, 2016 at 7:28
  • @fuuman: fixed typo in example code. Commented May 24, 2016 at 7:41

1 Answer 1

11

The functions defined in string module that are nowadays methods of str were deprecated in Python 2.4 and should not be used at all, though they were retained in later Python 2 versions for backward-compatibility. They were removed in Python 3.0.

  1. Why is the 2nd code working without import the string module?

Because it's a method of str type.

  1. Is there any performance improvement in using one over the other?

Well, string.find(x, y) calls x.find(y), but the performance doesn't matter here (see first sentence).

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

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.