- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Joining only adjacent words in list
In this article, we are going to learn how to join adjacent words in a list, not digits. Follow the below steps to solve the problem.
- Initialize the list.
- Find the words that are not digits using isalpha method.
- 4Join the words using join method.
- Add all the digits at the end by finding them using the isdigit method.
- Print the result.
Example
# initialzing the list strings = ['Tutorials', '56', '45', 'point', '1', '4'] # result result = [] words = [element for element in strings if element.isalpha()] digits = [element for element in strings if element.isdigit()] # adding the elements to result result.append("".join(words)) result += digits # printing the result print(result)
If you run the above code, then you will get the following result.
Output
['Tutorialspoint', '56', '45', '1', '4']
Let's see the code that uses a different way to solve the problem. We will use the filter method to filter the words and digits.
Example
# initialzing the list strings = ['Tutorials', '56', '45', 'point', '1', '4'] def isalpha(string): return string.isalpha() def isdigit(string): return string.isdigit() # result result = ["".join(filter(isalpha, strings)), *filter(isdigit, strings)] # printing the result print(result) ['Tutorialspoint', '56', '45', '1', '4']
If you run the above code, then you will get the following result.
Output
['Tutorialspoint', '56', '45', '1', '4']
Conclusion
If you have any queries in the article, mention them in the comment section.
Advertisements