15 Useful Python One-Liners for String Manipulation

In this article, we'll explore 15 Python one-liners that make string manipulation not just efficient but also fun.



15 Useful Python One-Liners for String Manipulation
Image by Author | Created on Canva

 

String manipulation is something you use often as a Python programmer—from cleaning messy data or processing user inputs, and more. But you can do quite a bit of string manipulation with only one line of Python.

In this article, we'll explore 15 Python one-liners that make string manipulation not just efficient but also fun. From filtering lists of strings to replacing vowels, we’ll code bite-sized examples along the way.

 

1. Convert Strings to Uppercase

 
This list comprehension iterates over each string in the and applies the upper() method, so we get copies of strings with all characters in uppercase.

strings = ["hello", "world", "python", "rocks"]
uppercase_strings = [s.upper() for s in strings]

 

Output:

['HELLO', 'WORLD', 'PYTHON', 'ROCKS']

 

2. Find Strings Containing a Specific Substring

 
This one-liner keeps only strings containing the substring “if” by using an if condition inside the list comprehension for filtering.

fruits = ["apple", "banana", "cherry", "apricot", "blueberry"]
filtered = [s for s in fruits if "ap" in s]

 

Output:

['apple', 'apricot']

 

3. Remove Leading and Trailing Whitespaces

 
Let’s use the strip() method to remove whitespaces (leading and trailing whitespaces) from all strings in the list.

strings = ["  fun ", " funky "]
trimmed_strings = [s.strip() for s in strings]

 

Output:

['fun', 'funky']

 

4. Reverse Strings

 
Let's reverse all strings in the list using string slicing like so: str[::-1].

to_do = ["code", "debug", "refactor"]
reversed_strings = [task[::-1] for task in to_do]

 

Output:

['edoc', 'gubed', 'rotcafer']

 

5. Concatenate Prefixes to Strings

 
To add a prefix (py-) to each string, you can use f-strings like so.

strings = ["code", "debug", "test"]
prefixed_strings = [f"py-{s}" for s in strings]

 

Output:

['py-code', 'py-debug', 'py-test']

 

6. Split Strings into Substrings

 
Let's split the strings into a list of strings with the split() method. The split() method uses whitespace as the default separator. Let's use it on a sample list.

strings = ["learn python", "python is fun"]
split_strings = [s.split() for s in strings]

 

Output:

[['learn', 'python'], ['python', 'is', 'fun']]

 

7. Replace Substrings in Strings

 
To replace a string with another, you can use the replace() method with the syntax str.replace(str1, str2). Here’s an example.

strings = ["Learn C", "Code in C"]
replaced_strings = [string.replace("C", "Python") for string in strings]

 

Output:

["Learn Python", "Code in Python"]

 

8. Count Occurrences of a Character

 
We can use the count() method to get the number of occurrences of a character in each string.

strings = ["apple", "banana", "cherry"]
char_counts = [s.count("a") for s in strings]

 

Output:

[1, 3, 0]

 

9. Join Strings

 
To join a list of strings into a single string, you can use the join() method.

strings = ["Python", "is", "great"]
sentence = " ".join(strings)

 

Output:

Python is great

 

10. Capitalize Strings

 
To capitalize strings in Python, you can use the capitalize() method.

strings = ["python", "rocks"]
capitalized_strings = [s.capitalize() for s in strings]

 

Output:

['Python', 'Rocks']

 

11. Find the Length of Strings

 
Let’s get the lengths of all strings in the list using the len() function.

strings = ["elephant", "cat", "dinosaur", "ant"]
lengths = [len(s) for s in strings]

 

Output:

[8, 3, 8, 3]

 

12. Check if Strings are Alphanumeric

 
Sometimes you may need to check if a string  contains only alphanumeric characters. To do so, you can use the isalnum() method which returns True if the string contains only alphanumeric characters and False otherwise.

strings = ["hello123", "world!", "python3.12", "rocks"]
is_alphanumeric = [s.isalnum() for s in strings]

 

Output:

[True, False, False, True]

 

13. Add Suffixes to Strings

 
Let’s use the + operator to concatenate the suffix “.py” to each string in the list.

files = ["main", "test", "app"]
suffixed_files = [file + ".py" for file in files]

 

Output:

['main.py', 'test.py', 'app.py']

 

14. Extract the First Letter of Each String

 
To get the first character of each string, you can use indexing like so: str[0].

strings = ["banana", "cherry", "date", "blueberry"]
first_letters = [s[0] for s in strings]

 

Output:

['b', 'c', 'd', 'b']

 

15. Sort Strings Alphabetically in Lowercase

 
The sorted() function sorts strings alphabetically—we ignore the case by using str.lower as the sorting key.

strings = ["Apple", "banana", "Cherry", "date"]
sorted_strings = sorted(strings, key=lambda s: s.lower())

 

Output:

['Apple', 'banana', 'Cherry', 'date']

 

Wrapping Up

 
That’s a wrap! If you list down some more string manipulation tasks, I’m sure you’ll be able to come up with one-liners for them as well.

Happy string manipulation!

If you’re interested in data cleaning, you may like 10 Useful Python One-Liners for Data Cleaning.
 
 

Bala Priya C is a developer and technical writer from India. She likes working at the intersection of math, programming, data science, and content creation. Her areas of interest and expertise include DevOps, data science, and natural language processing. She enjoys reading, writing, coding, and coffee! Currently, she's working on learning and sharing her knowledge with the developer community by authoring tutorials, how-to guides, opinion pieces, and more. Bala also creates engaging resource overviews and coding tutorials.


Get the FREE ebook 'KDnuggets Artificial Intelligence Pocket Dictionary' along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.

By subscribing you accept KDnuggets Privacy Policy


Get the FREE ebook 'KDnuggets Artificial Intelligence Pocket Dictionary' along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.

By subscribing you accept KDnuggets Privacy Policy

Get the FREE ebook 'KDnuggets Artificial Intelligence Pocket Dictionary' along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.

By subscribing you accept KDnuggets Privacy Policy

No, thanks!