Reputation: 23
I have this doing what I want it to (Take a file, shuffle the middle letters of the words and rejoin them), but for some reason, the spaces are being removed even though I'm asking it to split on spaces. Why is that?
import random
File_input= str(input("Enter file name here:"))
text_file=None
try:
text_file = open(File_input)
except FileNotFoundError:
print ("Please check file name.")
if text_file:
for line in text_file:
for word in line.split(' '):
words=list (word)
Internal = words[1:-1]
random.shuffle(Internal)
words[1:-1]=Internal
Shuffled=' '.join(words)
print (Shuffled, end='')
Upvotes: 0
Views: 87
Reputation: 13188
If you want the delimiter as part of the values:
d = " " #delim
line = "This is a test" #string to split, would be `line` for you
words = [e+d for e in line.split(d) if e != ""]
What this does is split the string, but return the split value plus the delimiter used. Result is still a list, in this case ['This ', 'is ', 'a ', 'test ']
.
If you want the delimiter as part of the resultant list, instead of using the regular str.split()
, you can use re.split()
. The docs note:
re.split(pattern, string[, maxsplit=0, flags=0])
Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.
So, you could use:
import re
re.split("( )", "This is a test")
And result:
['this', ' ', 'is', ' ', 'a', ' ', 'test']
Upvotes: 1