The everyday tools for cleaning and reshaping text, each one returning a new string or list.
Python · beginner · 7 min · 8 steps · free
line = " apples, pears, plums "
clean = line.strip()
parts = clean.split(", ")
joined = " & ".join(parts)
found = clean.find("pears")
has_plum = "plum" in clean
swapped = clean.replace("pears", "figs")
print(parts, joined, found, has_plum, swapped).strip() removes spaces (and newlines) from both ends..split(", ") cuts the text at every ", " and gives a list of the pieces." & ".join(parts) glues the list back together with " & " between items. The separator comes first..find gives the position where "pears" starts: 8. It gives -1 if not found.in just answers yes or no: True..replace swaps every "pears" for "figs" in a new string.line." & ".join(parts)in for "does it contain?" and find only when you need the positionAnswer: ["a", "b"]. split always returns a list.
Answer: -1. find returns -1 when the text is not there.
← Strings: Indexing and Slicing Text · f-strings: Putting Values into Text →