[Go to site: main page, start]

0% found this document useful (0 votes)
8 views22 pages

Python String Methods

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views22 pages

Python String Methods

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Regular String Methods

By
Abdulazeez Abdullahi (Binbaz)

Regular String Methods


These are methods you use every day with strings.

Method Simple Explanation & Example


capitalize First letter uppercase, rest lowercase "hello".capitalize() → "Hello"
casefold Makes string lowercase (stronger than lower)
center Centers string with padding: "abc".center(5, "*") → "*abc*"
count Counts substring occurrences: "banana".count("a") → 3
encode Converts string to bytes: "abc".encode() → b'abc'
endswith Checks if string ends with a substring: "abc".endswith("c") → True
expandtabs Converts tabs \t to spaces
find Finds first occurrence of substring, returns -1 if not found
format Replace placeholders: "Hello {}".format("World") → "Hello World"
format_map Like format, but uses a dictionary
index Like find, but raises error if not found
isalnum Checks if all letters/numbers "abc123".isalnum() → True
isalpha Checks if all letters "abc".isalpha() → True
isascii Checks if all characters are ASCII
isdecimal Checks if all characters are decimals "123".isdecimal() → True
isdigit Checks if all characters are digits
isidentifier Checks if string is a valid Python variable name
islower Checks if all letters are lowercase
isnumeric Checks if string contains numeric characters
isprintable Checks if string can be printed (no invisible characters)
isspace Checks if string has only spaces/tabs/newlines
istitle Checks if string is in title case "Hello World".istitle() → True
Method Simple Explanation & Example
isupper Checks if all letters are uppercase
join Joins iterable with string: ",".join(["a","b"]) → "a,b"
ljust Left-justifies string: "abc".ljust(5, "-") → "abc--"
lower Converts string to lowercase
lstrip Removes spaces (or chars) from left
maketrans Creates translation table for translate()
partition Splits string into 3 parts by separator
removeprefix Removes starting substring
removesuffix Removes ending substring
replace Replaces substring with another: "a b".replace("a","x") → "x b"
rfind Finds last occurrence of substring
rindex Last occurrence, raises error if not found
rjust Right-justifies string
rpartition Like partition but from right
rsplit Split string from right
rstrip Removes spaces/chars from right
split Splits string into list by separator
splitlines Splits string by newlines
startswith Checks if string starts with substring
strip Removes spaces from both sides
swapcase Switches case: "AbC".swapcase() → "aBc"
title Capitalizes first letter of each word
translate Replaces characters using translation table
upper Converts string to uppercase
zfill Fills string with zeros to reach desired length "5".zfill(3) → "005"

Summary of Key Patterns for Beginners


1. Case methods: lower(), upper(), swapcase(), capitalize(), title(), casefold().
2. Check methods: isalpha(), isalnum(), isdigit(), isnumeric(), islower(),
isupper(), istitle(), isspace(), isidentifier().
3. Search methods: find(), rfind(), index(), rindex(), startswith(), endswith(),
count().
4. Modify methods: strip(), lstrip(), rstrip(), replace(), removeprefix(),
removesuffix(), translate().
5. Split & join: split(), rsplit(), splitlines(), join(), partition(),
rpartition().
6. Padding & formatting: center(), ljust(), rjust(), zfill(), format(),
format_map().
7. Other utility: encode(), expandtabs(), isprintable(), maketrans().

1. capitalize()

Makes the first letter uppercase and others lowercase.

# Example 1
text = "hello world"
print([Link]()) # Output: Hello world

# Example 2
text = "PYTHON"
print([Link]()) # Output: Python

# Example 3
text = "123abc"
print([Link]()) # Output: 123abc (numbers stay same)

✅ Explanation: Only the first letter is capitalized; numbers and symbols stay the same.

2. casefold()

Converts string to lowercase, stronger than lower() (good for comparison).

# Example 1
text = "PYTHON"
print([Link]()) # Output: python

# Example 2
text = "ß" # German sharp s
print([Link]()) # Output: ss

# Example 3
text = "Hello World"
print([Link]()) # Output: hello world

✅ Explanation: Use when comparing strings ignoring case.

3. center()

Centers string with spaces (or a specified character).

# Example 1
text = "Hi"
print([Link](6)) # Output: ' Hi '
# Example 2
text = "Python"
print([Link](10, "*")) # Output: '**Python**'

# Example 3
text = "A"
print([Link](5, "-")) # Output: '--A--'

✅ Explanation: First argument = total length, second (optional) = padding character.

4. count()

Counts how many times a substring appears.

# Example 1
text = "banana"
print([Link]("a")) # Output: 3

# Example 2
text = "hello hello"
print([Link]("hello")) # Output: 2

# Example 3
text = "abc"
print([Link]("d")) # Output: 0

✅ Explanation: Returns number of times substring appears.

5. encode()

Converts string to bytes.

# Example 1
text = "hello"
print([Link]()) # Output: b'hello'

# Example 2
text = "Python"
print([Link]("utf-8")) # Output: b'Python'

# Example 3
text = "123"
print([Link]()) # Output: b'123'

✅ Explanation: Encodes string to bytes; needed for file writing or network transfer.
6. endswith()

Checks if string ends with a specific substring.

# Example 1
text = "[Link]"
print([Link](".py")) # Output: True

# Example 2
text = "[Link]"
print([Link](".pdf")) # Output: False

# Example 3
text = "Python"
print([Link]("on")) # Output: True

✅ Explanation: Returns True or False.

7. expandtabs()

Converts tab characters \t to spaces.

# Example 1
text = "a\tb\tc"
print([Link]()) # Output: 'a b c'

# Example 2
text = "1\t2\t3"
print([Link](4)) # Output: '1 2 3' (4 spaces per tab)

# Example 3
text = "\tHello"
print([Link](5)) # Output: ' Hello'

✅ Explanation: Default is 8 spaces per tab; can change with argument.

8. find()

Finds the first index of a substring, returns -1 if not found.

# Example 1
text = "banana"
print([Link]("a")) # Output: 1

# Example 2
text = "hello"
print([Link]("l")) # Output: 2
# Example 3
text = "abc"
print([Link]("z")) # Output: -1

✅ Explanation: Index starts at 0.

9. format()

Insert values into string placeholders {}.

# Example 1
text = "Hello {}"
print([Link]("World")) # Output: Hello World

# Example 2
text = "My name is {} and I am {} years old"
print([Link]("Ali", 20)) # Output: My name is Ali and I am 20 years old

# Example 3
text = "Number: {:.2f}"
print([Link](3.14159)) # Output: Number: 3.14

✅ Explanation: {} are placeholders, can format numbers too.

10. format_map()

Like format(), but uses a dictionary.

# Example 1
data = {"name": "Ali"}
text = "Hello {name}"
print(text.format_map(data)) # Output: Hello Ali

# Example 2
data = {"fruit": "apple", "count": 5}
text = "I have {count} {fruit}s"
print(text.format_map(data)) # Output: I have 5 apples

# Example 3
data = {"x": 10, "y": 20}
text = "Coordinates: {x}, {y}"
print(text.format_map(data)) # Output: Coordinates: 10, 20

✅ Explanation: Dictionary keys replace placeholders.


11. index()

Finds first index of substring, raises error if not found.

# Example 1
text = "banana"
print([Link]("a")) # Output: 1

# Example 2
text = "hello"
print([Link]("l")) # Output: 2

# Example 3
text = "abc"
# print([Link]("z")) # Error: ValueError

✅ Explanation: Similar to find(), but fails if substring is missing.

12. isalnum()

Checks if string has only letters and numbers.

# Example 1
text = "abc123"
print([Link]()) # Output: True

# Example 2
text = "hello!"
print([Link]()) # Output: False

# Example 3
text = "123"
print([Link]()) # Output: True

✅ Explanation: Spaces, symbols, and punctuation make it False.

13. isalpha()
Checks if string has only letters.

# Example 1
text = "hello"
print([Link]()) # Output: True

# Example 2
text = "hello123"
print([Link]()) # Output: False

# Example 3
text = "Python"
print([Link]()) # Output: True

✅ Explanation: Numbers or symbols make it False.

14. isascii()
Checks if string has only ASCII characters (English letters, numbers, symbols).

# Example 1
text = "hello"
print([Link]()) # Output: True

# Example 2
text = "こんにちは"
print([Link]()) # Output: False

# Example 3
text = "123!"
print([Link]()) # Output: True

✅ Explanation: ASCII = standard English characters.

15. isdecimal()
Checks if string contains only decimal numbers (0–9).

# Example 1
text = "12345"
print([Link]()) # Output: True

# Example 2
text = "123a"
print([Link]()) # Output: False

# Example 3
text = "½"
print([Link]()) # Output: False

✅ Explanation: Only full digits are True.


16. isdigit()
Checks if string contains only digits (similar to isdecimal(), includes some unicode digits).

# Example 1
text = "123"
print([Link]()) # Output: True

# Example 2
text = "3²"
print([Link]()) # Output: True (superscript 2 counts)

# Example 3
text = "123a"
print([Link]()) # Output: False

✅ Explanation: Includes some special numeric characters.

17. isidentifier()
Checks if string is a valid Python variable name.

# Example 1
text = "my_var"
print([Link]()) # Output: True

# Example 2
text = "123abc"
print([Link]()) # Output: False

# Example 3
text = "name!"
print([Link]()) # Output: False

✅ Explanation: Cannot start with number or have symbols except _.

18. islower()
Checks if all letters are lowercase.

# Example 1
text = "hello"
print([Link]()) # Output: True

# Example 2
text = "Hello"
print([Link]()) # Output: False

# Example 3
text = "123"
print([Link]()) # Output: False (no letters)

✅ Explanation: Numbers or symbols are ignored; only letters matter.

19. isnumeric()
Checks if string contains only numbers (includes digits, fractions, roman numerals, etc).

# Example 1
text = "123"
print([Link]()) # Output: True

# Example 2
text = "¼" # Fraction
print([Link]()) # Output: True

# Example 3
text = "abc123"
print([Link]()) # Output: False

✅ Explanation: More inclusive than isdigit() and isdecimal().

20. isprintable()
Checks if string can be printed (no control characters).

# Example 1
text = "Hello"
print([Link]()) # Output: True

# Example 2
text = "\n"
print([Link]()) # Output: False

# Example 3
text = "123!"
print([Link]()) # Output: True
✅ Explanation: Invisible characters like \n make it False.

21. isspace()
Checks if the string contains only spaces, tabs, or newlines.

# Example 1
text = " "
print([Link]()) # Output: True

# Example 2
text = "\t\n"
print([Link]()) # Output: True

# Example 3
text = " a "
print([Link]()) # Output: False

✅ Explanation: Any visible character makes it False.

22. istitle()
Checks if each word starts with uppercase and the rest lowercase.

# Example 1
text = "Hello World"
print([Link]()) # Output: True

# Example 2
text = "Hello world"
print([Link]()) # Output: False

# Example 3
text = "Python Is Fun"
print([Link]()) # Output: True

✅ Explanation: Good for checking titles or capitalized text.

23. isupper()
Checks if all letters are uppercase.
# Example 1
text = "HELLO"
print([Link]()) # Output: True

# Example 2
text = "Hello"
print([Link]()) # Output: False

# Example 3
text = "123!"
print([Link]()) # Output: False (no letters)

✅ Explanation: Numbers and symbols are ignored.

24. join()
Joins items of a list or iterable into one string, separated by the string.

# Example 1
words = ["I", "love", "Python"]
print(" ".join(words)) # Output: I love Python

# Example 2
numbers = ["1", "2", "3"]
print("-".join(numbers)) # Output: 1-2-3

# Example 3
letters = ["a", "b", "c"]
print("".join(letters)) # Output: abc

✅ Explanation: "separator".join(iterable) → combines items into a string.

25. ljust()
Left-justifies the string with padding on the right.

# Example 1
text = "Hi"
print([Link](5)) # Output: 'Hi '

# Example 2
text = "Python"
print([Link](10, "-")) # Output: 'Python----'

# Example 3
text = "A"
print([Link](3, "*")) # Output: 'A**'
✅ Explanation: First argument = total width, second (optional) = padding character.

26. lower()
Converts string to all lowercase.

# Example 1
text = "HELLO"
print([Link]()) # Output: hello

# Example 2
text = "Python Is Fun"
print([Link]()) # Output: python is fun

# Example 3
text = "123ABC"
print([Link]()) # Output: 123abc

✅ Explanation: Useful for case-insensitive comparisons.

27. lstrip()
Removes spaces (or characters) from the left side.

# Example 1
text = " hello"
print([Link]()) # Output: 'hello'

# Example 2
text = "!!!wow"
print([Link]("!")) # Output: 'wow'

# Example 3
text = "??abc??"
print([Link]("?")) # Output: 'abc??'

✅ Explanation: Only removes from the start, not the end.

28. maketrans()
Creates a translation table for translate() method.
# Example 1
table = [Link]("abc", "123")
text = "abc"
print([Link](table)) # Output: 123

# Example 2
table = [Link]("aeiou", "12345")
text = "hello"
print([Link](table)) # Output: h2ll4

# Example 3
table = [Link]("x", "y")
text = "xoxo"
print([Link](table)) # Output: yoyo

✅ Explanation: Maps characters to replace them easily.

29. partition()
Splits string into 3 parts: before, separator, after.

# Example 1
text = "hello world"
print([Link](" ")) # Output: ('hello', ' ', 'world')

# Example 2
text = "abc-def-ghi"
print([Link]("-")) # Output: ('abc', '-', 'def-ghi')

# Example 3
text = "python"
print([Link]("z")) # Output: ('python', '', '')

✅ Explanation: Always returns a tuple of 3 elements.

30. removeprefix()
Removes a specific starting substring.

# Example 1
text = "HelloWorld"
print([Link]("Hello")) # Output: World

# Example 2
text = "Python3"
print([Link]("Py")) # Output: thon3
# Example 3
text = "DataScience"
print([Link]("AI")) # Output: DataScience (prefix not found)

✅ Explanation: Only removes the exact start; rest stays unchanged.

31. removesuffix()
Removes a specific ending substring.

# Example 1
text = "HelloWorld"
print([Link]("World")) # Output: Hello

# Example 2
text = "Python3"
print([Link]("3")) # Output: Python

# Example 3
text = "DataScience"
print([Link]("AI")) # Output: DataScience (suffix not found)

✅ Explanation: Only removes from the end.

32. replace()
Replaces substring with another substring.

# Example 1
text = "I like apples"
print([Link]("apples", "oranges")) # Output: I like oranges

# Example 2
text = "banana"
print([Link]("a", "o")) # Output: bonono

# Example 3
text = "123-456"
print([Link]("-", ":")) # Output: 123:456

✅ Explanation: Replaces all occurrences unless you limit it.


33. rfind()
Finds last occurrence of substring, returns -1 if not found.

# Example 1
text = "banana"
print([Link]("a")) # Output: 5

# Example 2
text = "hello hello"
print([Link]("hello")) # Output: 6

# Example 3
text = "abc"
print([Link]("z")) # Output: -1

✅ Explanation: Similar to find() but starts searching from the right.

34. rindex()
Finds last occurrence of substring, raises error if not found.

# Example 1
text = "banana"
print([Link]("a")) # Output: 5

# Example 2
text = "hello hello"
print([Link]("hello")) # Output: 6

# Example 3
text = "abc"
# print([Link]("z")) # Error: ValueError

✅ Explanation: Like rfind() but fails if substring is missing.

35. rjust()
Right-justifies string, padding on the left side.

# Example 1
text = "Hi"
print([Link](5)) # Output: ' Hi'

# Example 2
text = "Python"
print([Link](10, "-")) # Output: '----Python'

# Example 3
text = "A"
print([Link](3, "*")) # Output: '**A'

✅ Explanation: Opposite of ljust().

36. rpartition()
Like partition(), but splits from the right.

# Example 1
text = "abc-def-ghi"
print([Link]("-")) # Output: ('abc-def', '-', 'ghi')

# Example 2
text = "python"
print([Link]("z")) # Output: ('', '', 'python')

# Example 3
text = "name@[Link]"
print([Link]("@")) # Output: ('name', '@', '[Link]')

✅ Explanation: Splits at last occurrence of separator.

37. rsplit()
Splits string from the right, can limit number of splits.

# Example 1
text = "a,b,c,d"
print([Link](",", 2)) # Output: ['a,b', 'c', 'd']

# Example 2
text = "python programming language"
print([Link](" ", 1)) # Output: ['python programming', 'language']

# Example 3
text = "apple,banana,orange"
print([Link](",")) # Output: ['apple', 'banana', 'orange']

✅ Explanation: Similar to split() but starts from the right.


38. rstrip()
Removes spaces (or characters) from the right side.

# Example 1
text = "hello "
print([Link]()) # Output: 'hello'

# Example 2
text = "!!!wow!!!"
print([Link]("!")) # Output: '!!!wow'

# Example 3
text = "abc???"
print([Link]("?")) # Output: 'abc'

✅ Explanation: Opposite of lstrip().

39. split()
Splits string into list by separator (default = space).

# Example 1
text = "I love Python"
print([Link]()) # Output: ['I', 'love', 'Python']

# Example 2
text = "a,b,c"
print([Link](",")) # Output: ['a', 'b', 'c']

# Example 3
text = "apple orange banana"
print([Link](" ")) # Output: ['apple', 'orange', 'banana']

✅ Explanation: Returns a list of words or items.

40. splitlines()
Splits string by line breaks.

# Example 1
text = "Hello\nWorld"
print([Link]()) # Output: ['Hello', 'World']

# Example 2
text = "Line1\rLine2\r\nLine3"
print([Link]()) # Output: ['Line1', 'Line2', 'Line3']

# Example 3
text = "No line breaks"
print([Link]()) # Output: ['No line breaks']

✅ Explanation: Great for reading multi-line text files.

41. startswith()
Checks if string starts with a specific substring.

# Example 1
text = "Python"
print([Link]("Py")) # Output: True

# Example 2
text = "hello world"
print([Link]("world")) # Output: False

# Example 3
text = "abc123"
print([Link]("abc")) # Output: True

✅ Explanation: Returns True or False.

42. strip()
Removes spaces (or characters) from both sides.

# Example 1
text = " hello "
print([Link]()) # Output: 'hello'

# Example 2
text = "!!!wow!!!"
print([Link]("!")) # Output: 'wow'

# Example 3
text = "?abc?"
print([Link]("?")) # Output: 'abc'

✅ Explanation: Combines lstrip() and rstrip().


43. swapcase()
Switches uppercase to lowercase and vice versa.

# Example 1
text = "Hello World"
print([Link]()) # Output: hELLO wORLD

# Example 2
text = "PYTHON"
print([Link]()) # Output: python

# Example 3
text = "abc123XYZ"
print([Link]()) # Output: ABC123xyz

✅ Explanation: Handy to toggle letter cases.

44. title()
Capitalizes first letter of each word.

# Example 1
text = "hello world"
print([Link]()) # Output: Hello World

# Example 2
text = "python programming"
print([Link]()) # Output: Python Programming

# Example 3
text = "123 abc"
print([Link]()) # Output: 123 Abc

✅ Explanation: Useful for titles or headings.

45. translate()
Replaces characters using a translation table from maketrans().

# Example 1
table = [Link]("abc", "123")
text = "abc"
print([Link](table)) # Output: 123
# Example 2
table = [Link]("aeiou", "12345")
text = "hello"
print([Link](table)) # Output: h2ll4

# Example 3
table = [Link]("x", "y")
text = "xoxo"
print([Link](table)) # Output: yoyo

✅ Explanation: Replace multiple characters easily.

46. upper()
Converts string to all uppercase.

# Example 1
text = "hello"
print([Link]()) # Output: HELLO

# Example 2
text = "Python 3"
print([Link]()) # Output: PYTHON 3

# Example 3
text = "abc123"
print([Link]()) # Output: ABC123

✅ Explanation: Good for case-insensitive comparison.

47. zfill()
Fills string with zeros on the left to reach desired length.

# Example 1
text = "5"
print([Link](3)) # Output: 005

# Example 2
text = "123"
print([Link](5)) # Output: 00123

# Example 3
text = "-42"
print([Link](5)) # Output: -0042
✅ Explanation: Useful for formatting numbers.

You might also like