String Methods

Built-in methods to transform and inspect strings.

Syntaxtext.upper() text.strip() text.replace(a, b)

Strings come with many built-in methods. A few essentials:

  • upper() / lower() — change case.
  • strip() — remove whitespace from both ends.
  • replace(a, b) — swap text.
  • split(sep) — break a string into a list.
  • startswith() / endswith() — test the ends.

Example

Example · python
text = '  Python  '
print(text.strip())
print(text.strip().upper())
print('cat'.replace('c', 'b'))
print('a,b,c'.split(','))

# Output:
# Python
# PYTHON
# bat
# ['a', 'b', 'c']

When to use it

  • A registration form strips leading/trailing whitespace from a submitted email before saving it.
  • A search feature converts user input to lowercase before comparing it to stored values.
  • A CSV processor splits each row string on commas to get a list of individual field values.

More examples

strip, lower, and replace

Chains strip(), lower(), and replace() to normalise a string in one expression.

Example · python
raw = '  Hello, World!  '
clean = raw.strip().lower().replace('world', 'python')
print(clean)

# Output:
# hello, python!

split and join

Splits a CSV row into a list with split() then reassembles it with a different separator.

Example · python
csv_row = 'Alice,30,Engineer'
fields = csv_row.split(',')
print(fields)           # ['Alice', '30', 'Engineer']
rejoined = ' | '.join(fields)
print(rejoined)         # Alice | 30 | Engineer

startswith, endswith, find

Uses endswith(), startswith(), and find() to inspect and locate substrings.

Example · python
filename = 'report_2024.pdf'
print(filename.endswith('.pdf'))    # True
print(filename.startswith('rep'))  # True
idx = filename.find('2024')
print(idx)                          # 7

Discussion

  • Be the first to comment on this lesson.