Swayam Shah
Swayam Shah

Reputation: 111

How to retain only alphabets from a string of words

Below is my code to remove all numbers and special character from a string:

string = 'Date: 2008-01-04 18:08:50 -0500 (Fri, 04 Jan 2008)'
words = ""
for char in string:
    if char.isalpha():
        words += char
print(words)

The output I get is:

DateFriJan

The output I need:

Date Fri Jan

How can I split the string with the spaces included so these are separate words

Upvotes: 0

Views: 94

Answers (1)

raspiduino
raspiduino

Reputation: 681

You can use:

for char in string:
    if char.isalpha():
        words += char
        if not string[(string.index(char) + 1)].isalpha():
            words += " "
print(words)

You will get Date Fri Jan

Basicly it just check if the next char in the string is not alpha, then it will add a space to words

Upvotes: 1

Related Questions