![]() |
VOOZH | about |
Python provides an wide range of built-in methods that make string manipulation simple and efficient. In this article, we'll explore several techniques for modifying strings in Python.
Start with doing a simple string modification by changing the its case:
One of the simplest ways to modify a string is by changing its case using string.upper() method which converts all characters in the string to uppercase.
HELLO WORLD
Other methods of changing case in a python strings are:
Let's take a look at other cases of string modification:
Table of Content
We can replace parts of a string using replace() method. This method takes two arguments: 1) old substring we want to replace and 2) new substring we want to replace it with.
Example:
I love programming
The replace() method returns a new string, so the original string is not modified in place (since strings are immutable in Python).
Sometimes, strings may have unwanted spaces at the beginning or end. To remove these, we can use the strip() method. This method removes any leading and trailing whitespace from the string.
Hello World!
We can also use lstrip() to remove leading spaces and rstrip() to remove trailing spaces.
Concatenating strings means joining two or more strings together. In Python, we can do this using the + operator.
Hello World Python is awesome
We can also use join() when concatenating a list of strings.
String slicing allows you to extract a portion of a string. We can specify a starting and ending index and Python will return a substring. We can also use the step parameter to skip characters.
Hello Python! Hello Hlo yhn
To check if a string contains a certain substring, we can use in keyword .
True
The in keyword returns True if the substring is found . We can also use find() method which returns the index of the first occurrence of the substring (or -1 if it's not found).
Python allows we to format strings in a readable way using f-strings (formatted string literals), which were introduced in Python 3.6. We can insert variables or expressions inside a string using curly braces {}.
name - Geek
For earlier versions of Python, we can use the format() method.
You can learn more about string methods with our String Methods Article.