Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Joining only adjacent words in list
In this article, we are going to learn how to join adjacent words in a list while keeping digits separate. This technique is useful when processing mixed data that contains both text and numeric values.
Approach
To solve this problem, we need to ?
- Initialize the list with mixed string and numeric elements
- Separate words from digits using
isalpha()andisdigit()methods - Join all the words together using the
join()method - Add all digits to the result list while maintaining their order
Using List Comprehension
The most straightforward approach uses list comprehension to separate words and digits ?
# initializing the list
strings = ['Tutorials', '56', '45', 'point', '1', '4']
# result list
result = []
# separate words and digits
words = [element for element in strings if element.isalpha()]
digits = [element for element in strings if element.isdigit()]
# join words and add to result
result.append("".join(words))
result += digits
# printing the result
print(result)
The output of the above code is ?
['Tutorialspoint', '56', '45', '1', '4']
Using Filter Method
An alternative approach uses the filter() method with helper functions to separate elements ?
# initializing the list
strings = ['Tutorials', '56', '45', 'point', '1', '4']
def is_alpha(string):
return string.isalpha()
def is_digit(string):
return string.isdigit()
# create result using filter and unpacking
result = ["".join(filter(is_alpha, strings)), *filter(is_digit, strings)]
# printing the result
print(result)
The output of the above code is ?
['Tutorialspoint', '56', '45', '1', '4']
Comparison
| Method | Readability | Best For |
|---|---|---|
| List Comprehension | High | Simple filtering and clear logic |
| Filter Method | Moderate | Functional programming approach |
Conclusion
Both methods effectively join adjacent words while preserving digits separately. The list comprehension approach is more readable, while the filter method offers a functional programming style for the same result.
Advertisements
