Dealing with strings that are multiple words

Basically, doing things with a simple string, like “Apple” is easy. The big problem comes when the string is actually a phrase, like “This apple is too expensive”.

With a single word string, it’s easy to manipulate it statically, because you know it’s one word, the end is always going to be the end of that word (Word[-1]) the beggining always the beggining (Word[0]). Things start to go heavy with phrases where it’s a pain to get the beggining of a word and the end of it, or the middle letter of it, or whatever, since Python and other programming languages take the WHOLE string into account, not every word.


In my horrible attempt here, I tried to swap the First and the Last letter of everyword in a string. Something told me (not sure if it is correct) that by using split() function you can actually split the words into a list, so I tried doing that, and work with each word.

My god I just noticed I did i = 0 and i = +1 in the same identation.

Anyway, ignore these low QIs mistakes, I was getting so anxious doing this that I couldn’t even think throught.

Edit: no wait, I didn’t wtf

Actually managed to solve it on my own. Not sure if this is the best and simplest way, but, well… It’s here for whoever in the world wish to know how to work with multiple words in a string. Note that this only works if the Words are separated by a blank space (space on keyboard), because the string.split(), in parenthesis, you should pass the argument you want to split the words base upon. Default is blank space. If you’d wish to separate by , or . you should split(‘.’) or split(',).

Some things to consider:

  • very few of us write code in Photoshop so please post/paste text and format it as code using backtics (```)
  • it’s useful to describe what problem you try to solve (this appears to be: reverse every word in sentence)
  • there is built-in function reversed
  • if for some reason (homework?) built-in function can’t be used then [::-1] is the simple way to reverse
  • In real life sentences there are punctuations and they should be dealt.
# split string to words, reverse every word and create new string from reversed words
>>> s = "The Quick Brown Fox Jumps Over The Lazy Dog A B C D EE"
>>> ' '.join([word[::-1] for word in s.split()])
'ehT kciuQ nworB xoF spmuJ revO ehT yzaL goD A B C D EE'

Sorry about the image posting. I was trying to copy and paste the code itself, but the Reply Box wasn’t properly displaying identations.

oh yes that works, but how to close it?``` das

deleted previous post to answer it as REPLY