David542
David542

Reputation: 110173

Separating a string in Python

How would I separate characters once I have a string of unseparated words?

For example to translate "take the last character of the suffix and add a space to it every time ("aSuffixbSuffixcSuffix" --> "aSuffix bSuffix cSuffix").`

Or, more generally, to replace the x-nth character, where x is any integer (e.g., to replace the 3rd, 6th, 9th, etc. character some something I choose).

Upvotes: 3

Views: 606

Answers (3)

pmav99
pmav99

Reputation: 2057

You could use the replace method of strings. Check the documentation

initial = "aSuffixbSuffixcSuffix"

final = initial.replace("Suffix", "Suffix ")
print(final)

Upvotes: 1

Mike Lewis
Mike Lewis

Reputation: 64147

   str = "SuffixbSuffixcSuffix"

   def chunk_str(str, chunk_size):
        return [str[i:i+chunk_size] for i in range(0, len(str), chunk_size)]

   " ".join(chunk_str(str,3))

returns:

'Suf fix bSu ffi xcS uff ix'

Upvotes: 2

nmichaels
nmichaels

Reputation: 50951

Assuming you're getting your string from this question, the easiest way is to not cram all the strings together in the first place. Your original create_word could be changed to this:

def create_word(suffix):
    letters="abcdefghijklmnopqrstuvwxyz"
    return [i + suffix for i in letters]

Then you'd be able to take e and ''.join(e) or ' '.join(e) to get the strings you want.

Upvotes: 2

Related Questions