1

i want to ask how we can replace only the first word in regular expression in python i do this code :

print "number of all KSU occurrences %i "%len(re.findall("ksu",string,re.IGNORECASE))
print "number of all KSU at end lof line %i"%len(re.findall("ksu\n",string,re.IGNORECASE))

and this is my txt file

hello i'm student in KSU i love ksu , i like ksu , i KSU ksu KSU

i just want to replace only first ksu ( ignoring case ) into King Saud University

1
  • So, how do you like KSU? Commented Oct 1, 2013 at 12:22

1 Answer 1

1

re.sub() takes a count parameter:

re.sub(r"\bksu\b", "King Saud University", string, flags=re.I, count=1)
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.