Skip to content

Instantly share code, notes, and snippets.

@PramodDutta
Last active February 6, 2024 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PramodDutta/d0744a067417b82d36d352ae907e4a16 to your computer and use it in GitHub Desktop.
Save PramodDutta/d0744a067417b82d36d352ae907e4a16 to your computer and use it in GitHub Desktop.

Strings Functions Explained - TheTestingAcademy

Python strings come with a variety of built-in methods that allow you to perform different operations on them. Here's a list of all common string methods available in Python, along with examples for each. This list is not exhaustive but covers the most frequently used methods.

1. capitalize()

  • Description: Converts the first character of the string to uppercase.
  • Example:
s = 'hello world'
print(s.capitalize())  # Output: 'Hello world'

2. casefold()

  • Description: Converts string to lowercase, designed for caseless matching.
  • Example:
s = 'HELLO World'
print(s.casefold())  # Output: 'hello world'

3. center(width, fillchar)

  • Description: Returns a centered string of length width.
  • Example:
s = 'hello'
print(s.center(20, '*'))  # Output: '*******hello********'

4. count(substring, start, end)

  • Description: Returns the number of occurrences of a substring in the string.
  • Example:
s = 'hello world'
print(s.count('o'))  # Output: 2

5. encode(encoding="utf-8", errors="strict")

  • Description: Returns an encoded version of the string as a bytes object.
  • Example:
s = 'hello world'
print(s.encode())  # Output: b'hello world'

6. endswith(suffix, start, end)

  • Description: Returns True if the string ends with the specified suffix.
  • Example:
s = 'hello world'
print(s.endswith('world'))  # Output: True

7. expandtabs(tabsize=8)

  • Description: Replaces tabs in a string with the specified number of spaces.
  • Example:
s = 'hello\tworld'
print(s.expandtabs(4))  # Output: 'hello   world'

8. find(sub, start, end)

  • Description: Returns the lowest index in the string where substring sub is found.
  • Example:
s = 'hello world'
print(s.find('world'))  # Output: 6

9. format(*args, **kwargs)

  • Description: Formats the string using format specifiers.
  • Example:
s = 'Hello, {}'
print(s.format('world'))  # Output: 'Hello, world'

10. format_map(mapping)

  • Description: Formats the string using a dictionary.
  • Example:
s = 'Hello, {name}'
print(s.format_map({'name': 'world'}))  # Output: 'Hello, world'

11. index(sub, start, end)

  • Description: Like find(), but raises ValueError when the substring is not found.
  • Example:
s = 'hello world'
print(s.index('world'))  # Output: 6

12. isalnum()

  • Description: Returns True if all characters in the string are alphanumeric.
  • Example:
s = 'hello123'
print(s.isalnum())  # Output: True

13. isalpha()

  • Description: Returns True if all characters in the string are alphabetic.
  • Example:
s = 'hello'
print(s.isalpha())  # Output: True

14. isdecimal()

  • Description: Returns True if all characters in the string are decimal characters.
  • Example:
s = '123'
print(s.isdecimal())  # Output: True

15. isdigit()

  • Description: Returns True if all characters in the string are digits.
  • Example:
s = '123'
print(s.isdigit())  # Output: True

16. isidentifier()

  • Description: Returns True if the string is a valid identifier according to Python syntax.
  • Example:
s = 'hello_world'
print(s.isidentifier())  # Output: True

17. islower()

  • Description: Returns True if all cased characters in the string are lowercase.
  • Example:
s = 'hello world'
print(s.islower())  # Output: True

18. isnumeric()

  • Description: Returns True if all characters in the string are numeric characters.
  • Example:
s = '123'
print(s.isnumeric())  # Output: True

19. isprintable()

  • Description:

Returns True if all characters in the string are printable or the string is empty.

  • Example:
s = 'hello world'
print(s.isprintable())  # Output: True

20. isspace()

  • Description: Returns True if all characters in the string are whitespace.
  • Example:
s = '   '
print(s.isspace())  # Output: True

21. istitle()

  • Description: Returns True if the string is a title-cased string.
  • Example:
s = 'Hello World'
print(s.istitle())  # Output: True

22. isupper()

  • Description: Returns True if all cased characters in the string are uppercase.
  • Example:
s = 'HELLO WORLD'
print(s.isupper())  # Output: True

23. join(iterable)

  • Description: Joins the elements of an iterable to the string.
  • Example:
s = '-'
print(s.join(['hello', 'world']))  # Output: 'hello-world'

24. ljust(width, fillchar)

  • Description: Returns a left-justified string of length width.
  • Example:
s = 'hello'
print(s.ljust(10, '*'))  # Output: 'hello*****'

25. lower()

  • Description: Converts all characters in the string to lowercase.
  • Example:
s = 'HELLO WORLD'
print(s.lower())  # Output: 'hello world'

26. lstrip(chars)

  • Description: Returns a copy of the string with leading characters removed.
  • Example:
s = '   hello world'
print(s.lstrip())  # Output: 'hello world'

27. partition(sep)

  • Description: Splits the string at the first occurrence of sep.
  • Example:
s = 'hello world'
print(s.partition(' '))  # Output: ('hello', ' ', 'world')

28. replace(old, new, count)

  • Description: Returns a string where all occurrences of old have been replaced by new.
  • Example:
s = 'hello world'
print(s.replace('world', 'Python'))  # Output: 'hello Python'

29. rfind(sub, start, end)

  • Description: Returns the highest index in the string where substring sub is found.
  • Example:
s = 'hello world, hello Python'
print(s.rfind('hello'))  # Output: 13

30. rindex(sub, start, end)

  • Description: Like rfind(), but raises ValueError when the substring is not found.
  • Example:
s = 'hello world, hello Python'
print(s.rindex('hello'))  # Output: 13

31. rjust(width, fillchar)

  • Description: Returns a right-justified string of length width.
  • Example:
s = 'hello'
print(s.rjust(10, '*'))  # Output: '*****hello'

32. rpartition(sep)

  • Description: Splits the string at the last occurrence of sep.
  • Example:
s = 'hello world, hello Python'
print(s.rpartition(' '))  # Output: ('hello world, hello', ' ', 'Python')

33. rsplit(sep=None, maxsplit=-1)

  • Description: Splits the string at the separator sep and returns a list of strings.
  • Example:
s = 'hello world hello Python'
print(s.rsplit(' ', 1))  # Output: ['hello world hello', 'Python']

34. rstrip(chars)

  • Description: Returns a copy of the string with trailing characters removed.
  • Example:
s = 'hello world   '
print(s.rstrip())  # Output: 'hello world'

35. split(sep=None, maxsplit=-1)

  • Description: Splits the string at the separator sep and returns a list.
  • Example:
s = 'hello world hello Python'
print(s.split())  # Output: ['hello', 'world', 'hello', 'Python']

36. splitlines(keepends=False)

  • Description: Splits the string at line breaks and returns a list of lines.
  • Example:
s = 'hello\nworld'
print(s.splitlines())  # Output: ['hello

', 'world']

37. startswith(prefix, start, end)

  • Description: Returns True if the string starts with the specified prefix.
  • Example:
s = 'hello world'
print(s.startswith('hello'))  # Output: True

38. strip(chars)

  • Description: Returns a copy of the string with leading and trailing characters removed.
  • Example:
s = '   hello world   '
print(s.strip())  # Output: 'hello world'

39. swapcase()

  • Description: Converts uppercase characters to lowercase and vice versa.
  • Example:
s = 'Hello World'
print(s.swapcase())  # Output: 'hELLO wORLD'

40. title()

  • Description: Returns a title-cased version of the string.
  • Example:
s = 'hello world'
print(s.title())  # Output: 'Hello World'

41. translate(table)

  • Description: Returns a copy of the string in which each character has been mapped through a given translation table.
  • Example:
# Translation table to replace 'h' with 'j'
trans = str.maketrans('h', 'j')
s = 'hello world'
print(s.translate(trans))  # Output: 'jello world'

42. upper()

  • Description: Converts all characters in the string to uppercase.
  • Example:
s = 'hello world'
print(s.upper())  # Output: 'HELLO WORLD'

43. zfill(width)

  • Description: Pads the string on the left with zeros to fill width.
  • Example:
s = '42'
print(s.zfill(5))  # Output: '00042'

These methods are part of the core Python language and provide powerful tools for manipulating strings in various ways.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment