0

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='')
4
  • This is the nature of split. The separator is treated as an unwanted delimiter and discarded. Commented Oct 13, 2013 at 1:54
  • So is there a way to keep it in? Commented Oct 13, 2013 at 1:59
  • Check out the answer I've provided, it shows two ways depending on which kind of result list you're looking for. Commented Oct 13, 2013 at 2:06
  • I also see you are a new user and that this is your first question, so please check out What should I do when someone answers my question? and accept the answer that is the best solution to your problem. Commented Oct 13, 2013 at 2:11

1 Answer 1

1

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']

Sign up to request clarification or add additional context in comments.

2 Comments

Well I thought it worked... Instead of putting a string in the re.split, is there any way to put the variable? Because it doesn't seem re.split works with variables.
Works fine with variables for me here: ideone.com/WvNVuG If you're having trouble with re.split and can't figure it out with the code I just linked, try making a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.