Reverse word order
October 23, 2019 · View on GitHub
The problem
Reverse the word in a sentence.
For example, if the input string is “Hello young Programmer”, the output will be “Programmer young Hello”
Hints
There are two methods that you can call on a string. One is called split(). If you don’t pass any parameter to this function, it will split the string by whitespace.
The opposite of split is join. You can write what you want to join string by. And then pass the array to it.
For example, if you want to join a list elements by whitespace, you can write the whitespace and then join like bellow
str ='Hello young Programmer'
words = str.split()
print(words)
together = ' '.join(words)
print(together)
Solution
def reverse_words(sentence):
words = sentence.split()
words.reverse()
return " ".join(words)
usr_input = input("Enter a sentence: ")
reverse = reverse_words(usr_input)
print('Reversed words are: ', reverse)
Explanation
Once you understand the split and the join method, this code should become super easy for you.
If you have any confusion, let us know.
Quiz
What is the purpose of the split method on a string?
- Breakdown string into elements of a list
- Split the string if it has no whitespace
- Adds some splitting characteristics
Show Answer
The answer is: 1
Quiz
How would you split a string by the character a?
- str.split()
- str.split(“ ”)
- str.split(‘a’)
Show Answer
The answer is: 3
Quiz
How would you join each string in the words list by the hyphen(-)?
- words.join(“-”)
- words.split(“-”)
- “-”.join(words)
Show Answer
The answer is: 3
Reverse domain
Let’s say, you have the website name www.programming-hero.com
Now you want to reverse the domain name: com.programming-hero.www
site='www.programming-hero.com'
parts = site.split('.')
parts.reverse()
rev = '.'.join(parts)
print(rev)
Try it on Programming Hero Alternatively, you can write the whole code in one line.
site='www.programming-hero.com'
rev = '.'.join(reversed(site.split('.')))
print(rev)
take Away
The split method breaks string into elements of a list.
tags: programming-hero python python3 problem-solving programming coding-challenge interview learn-python python-tutorial programming-exercises programming-challenges programming-fundamentals programming-contest python-coding-challenges python-problem-solving
