Ravindra BagaleCourses & study guides मराठी Track your progress

Python Strings Tutorial: Slicing, f-strings and String Methods with Examples

P3.5 How to Check Text with in, startswith and endswith

Why. You often need to find rows: all emails from one company, all codes starting with "BLK", all files ending with ".csv".

What. These checks give True or False.

  • "a" in text — is "a" anywhere in the text?
  • text.startswith("BLK") — does it start with BLK?
  • text.endswith(".csv") — does it end with .csv?

How.

Check and act

  1. Pick the check you need.
  2. Make the text lower case first if case may differ.
  3. Use the True/False result in an if (next chapters) or a filter (pandas).

Worked example A — Is a word inside?.

Step 1 — What we do. A support ticket in Bengaluru mentions a refund.

Step 2 — Type and run this code.

ticket = "Customer wants a refund for order 778"
print("refund" in ticket)
print("cancel" in ticket)

Step 3 — Output you should see.

True
False

Step 4 — What it means. in checks the whole text. The first is True, the second False.

Worked example B — Start and end checks.

Step 1 — What we do. We check an order code and a file name.

Step 2 — Type and run this code.

code = "BLK-PUN-1001"
file = "sales_march.csv"
print(code.startswith("BLK"))
print(file.endswith(".csv"))

Step 3 — Output you should see.

True
True

Step 4 — What it means. Both are True. In pandas you will write df["code"].str.startswith("BLK") with the same meaning.

Ravindra Bagale's Tip

Make both sides lower case before checking: "refund" in text.lower(). Then "Refund" and "REFUND" also match.

Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.