Skip to content
Advertisement

Splitting long string without spaces into words with certain length

So I have a really long string from a text document made entirely up of 7-letter words. I need to separate them and store each 7-letter word into an list.

The text document is originally made up of 7-letter words each separated by lines. A small part of it is shown below: Screenshot of the text document

After the space is removed it looks like this: Screenshot of string with lines removed A solution of how to store them in a list straight from the form of being separated in lines would also work for me.

I used this to remove the new lines:

with open(r"C:UsersHPDesktopinput.txt", 'r') as file:
    data = file.read().replace('n', '')
print(data)

Thanks.

Advertisement

Answer

Use the split function, which creates a list of tokens based on the provided delimiter. You can provide a ‘n’ delimiter, something like this:

with open('input.txt', 'r') as file:
    data = file.read()
separated_list = data.split('n')
print(separated_list)

output:

['abc', 'def', 'hij']
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement