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 inPython.
Start with doing a simplestringmodification by changing the its case:
Changing Case
One of the simplest ways to modify a string is by changing its case usingstring.upper() method which converts all characters in the string to uppercase.
Pythons="hello world"print(s.upper())
Other methods of changing case in a python strings are:
- lower(): Converts all characters in the string to lowercase.
- capitalize(): Capitalizes the first character of the string and makes the rest lowercase.
- title():Capitalizes the first letter of each word in the string.
- swapcase(): Swap the cases of all characters in a string
- capitalize(): Convert the first character of a string to uppercase
Let's take a look at other cases of string modification:
Replacing Substrings
We can replace parts of a string usingreplace() method. This method takes two arguments: 1) old substring we want to replace and 2) new substring we want to replace it with.
Example:
Pythons1="I love Python"s2=s1.replace("Python","programming")print(s2)
The replace() method returns a new string, so the original string is not modified in place (since strings are immutable in Python).
Trimming Whitespace
Sometimes, strings may have unwanted spaces at the beginning or end. To remove these, we can use thestrip() method. This method removes any leading and trailing whitespace from the string.
Pythons=" Hello World! "print(s.strip())
We can also uselstrip() to remove leading spaces andrstrip() to remove trailing spaces.
Concatenating Strings
Concatenating strings means joining two or more strings together. In Python, we can do this using the + operator.
Pythons1="Hello"s2="World"print(s1+" "+s2)
OutputHello WorldPython is awesome
We can also use join() when concatenating alist of strings.
Slicing 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.
Pythons="Hello, Python!"print(s[0:5])# Output: "Hello" (characters from index 0 to 4)print(s[7:])# Output: "Python!" (characters from index 7 to the end)print(s[:5])# Output: "Hello" (characters from the start to index 4)print(s[::2])# Output: "Hoo yhn" (every second character)
OutputHelloPython!HelloHlo yhn
Checking for Substrings
To check if a string contains a certain substring, we can usein keyword.
Pythons="Python is fun"print("Python"ins)
The in keyword returns True if the substring is found . We can also usefind() method which returns the index of the first occurrence of the substring (or -1 if it's not found).
Formatting Strings
Python allows we to format strings in a readable way usingf-strings (formatted string literals), which were introduced in Python 3.6. We can insert variables or expressions inside a string using curly braces {}.
Pythons="Geek"print(f"name -{s}")
For earlier versions of Python, we can use theformat() method.
You can learn more about string methods with ourString Methods Article.