String methods in Python are built-in functions that operate on string objects. These methods provide a variety of operations for manipulating and working with strings, allowing you to perform tasks such as formatting, searching, modifying, and extracting information from strings.
Here are some common string methods in Python:
str.upper()
and str.lower()
:
pythonCopy codemy_string = "Hello, World!"
upper_case = my_string.upper()
lower_case = my_string.lower()
str.capitalize()
and str.title()
:
pythonCopy codemy_string = "hello, world!"
capitalized = my_string.capitalize()
title_case = my_string.title()
str.strip()
, str.lstrip()
, and str.rstrip()
:
pythonCopy codemy_string = " Python "
stripped = my_string.strip()
left_stripped = my_string.lstrip()
right_stripped = my_string.rstrip()
str.replace(old, new[, count])
:
count
parameter limits the number of replacements.pythonCopy codemy_string = "Hello, World!"
replaced = my_string.replace("Hello", "Hi")
str.find(substring[, start[, end]])
and str.index(substring[, start[, end]])
:
find
method returns -1 if the substring is not found, while index
raises a ValueError
.pythonCopy codemy_string = "Hello, World!"
position = my_string.find("World")
str.count(substring[, start[, end]])
:
pythonCopy codemy_string = "Hello, Hello, World!"
count = my_string.count("Hello")
str.startswith(prefix[, start[, end]])
and str.endswith(suffix[, start[, end]])
:
pythonCopy codemy_string = "Hello, World!"
starts_with_hello = my_string.startswith("Hello")
ends_with_world = my_string.endswith("World")
str.split(sep=None, maxsplit=-1)
:
sep
). The optional maxsplit
parameter limits the number of splits.pythonCopy codemy_string = "apple,orange,banana"
fruits = my_string.split(",")
str.join(iterable)
:
pythonCopy codefruits = ["apple", "orange", "banana"]
joined_string = ",".join(fruits)
These are just a few examples of the many string methods available in Python. String methods make it convenient to perform a wide range of operations on strings without having to write custom functions for each task.