Reverse an input using tuples Python - python

I want to be able to write function that will reverse a phrase such as 'Hello World' into 'World Hello'. So far i can get to:
def reverser():
print('Please input a phrase')
inputphrase=input()
if ' ' in inputphrase:
after this I'm assuming you need to slice the string and then that slice gets stored in a tuple, and at the end the variables will print out.

It would be stored in a list, not a tuple. Here's how you do it in 2 lines:
my_input = input('Your phrase: ')
print(*reversed(my_input.split())) # Python 3
or
print ' '.join(reversed(a.split())) # Python 2
So the function would be:
func = lambda x: reversed(x.split())
which will return a list of reversed words from the phrase if called as follows:
arg = input('Enter a phrase :')
splitted = func(arg)
print(*splitted) # or in Python 2: print ' '.join(splitted)

you can use the reversed built-in
def reverser():
return ' '.join(reversed(input('Please input a phrase:').split()))
the input string is split on whitespace, then passed to reversed, then joined again
For example use it as
>>> print(reverser())
Please input a phrase:hello world how are you
you are how world hello

>>> inputphrase = "Hello World"
>>> parts = inputphrase.split(' ')
>>> parts.reverse()
>>> ' '.join(parts)
'World Hello'
You don't need to test if ' ' in inputphrase: as parts will contain just a single item in that case.
It's a good idea to make your functions have a single purpose. You should have one function for getting the input, and another for reversing it.

Python programming language provides a neat syntax to reverse a
tuple.The syntax is var[::-1] which returns a reverse copy of the var.
Example:
def reverser():
inputphrase = tuple(x.strip() for x in raw_input("Please input a phrase: ").split(' '))
return inputphrase[::-1]
print reverser()
Output:
Please input a phrase: Hello World
('World', 'Hello')
Or you can do it this way.
def reverser():
inputphrase = tuple(x.strip() for x in raw_input("Please input a phrase: ").split(' '))
return tuple(reversed(inputphrase))
print reverser()
Output:
Please input a phrase: Hello World.
('World.', 'Hello')

Related

how I can change whitespaces between words of a string in print order?

i was writing a code to input a sentence of user then change its whitespaces to ... and print the sentence.
hi rocks
I intended to input a sentence and change its whitespaces to "..."
I wrote this code:
a=input("inter your sentence: ")
#split in to n str
#print every str with ... as whitespace
a=a.split()
for x in a:
print(x, sep='...',end="")
if I input this is a test, i expected to see
this...is...a...test
but it doesn't work
it gives me
"thisisatest
do this.
a=input("inter your sentence: ")
#split in to n str
#print every str with ... as whitespace
a=a.split()
print(*a, sep='...')
Or do this.
a=input("inter your sentence: ")
#split in to n str
#print every str with ... as whitespace
a=a.split()
final_a = '...'.join(a)
print(final_a)
OUTPUT (for input this is a test)
this...is...a...test
Replying OP's comment. "so what you think about this one for x in range(0,10): print (x ,sep='...', end="") it didn't work too"
for x in range(0,10):
print(x ,sep='...', end="")
Note: sep seprate args provide in print method, Default sep=" "
Example:
print("one","1", sep="-->")
# Output: one-->1
And end: When every args print in terminal then print see the end value and print it in terminal. Default end="\n" \n → newline
Example:
for a in range(0, 10):
print(a, end=".|.")
#Output= 0.|.1.|.2.|.3.|.4.|.5.|.6.|.7.|.8.|.9.|.
# Here when 0 prints then print method also print `end`'s value after that, and 1 then `end`'s value and so on.
Answer for your comment's question can be this.
for x in range(0,10):
print(x,end='...')
Output
As I say end's value print after every print method args print, so '...' also prints after x last value(9).
0...1...2...3...4...5...6...7...8...9...
str.replace can be used to replace one or multiple characters of same ASCII value to another. In your case, it would be:
a=input("inter your sentence: ")
a=a.replace(' ', '...')
print(a)
You can make use of the Python join and split functions in this case:
The code snippet:
inputSentence = input("Enter your sentence: ")
print("...".join(inputSentence.split()))
The output:
Enter your sentence: This is a test
This...is...a...test

Irregular display when printing functions

I'm trying to write a script that when called prompts a user for a string and it displays the string forward, backward, tests if 2 strings are the same, and tests if a string is a palindrome. I want to test the individual functions for correctness before I input a menu, however the output when calling palindrome() function seems irregular. Any help on why the two statements in the palindrome() function prints this way would be appreciated.
string = raw_input('Enter a string\n>>>')
def forward():
for i in string:
print i,
return str(i)
def backwards():
back = len(string) - 1
while back > 0:
print string[back],
back -= 1
return str(string[back])
def match():
next_string = raw_input('Enter another string')
if string.upper() == next_string.upper():
print 'the strings ', string, ' and ', next_string, ' match.'
else:
print 'the strings ', string, ' and ', next_string, ' do not match.'
def palindrome():
print backwards() # When I don't print this call it only displays the last value in the string
y = forward() # When I do print this call it displays the last value in the string twice
# This is the only way where these calls are opposite
palindrome()

Count the number of spaces between words in a string

I am doing this problem on Hackerrank,and I came up with the idea, which includes splitting the input and join it afterwards (see my implementation below). However, one of the test cases contains the input (hello< multiple spaces> world), which crashed my code because the input string has more than 1 space between each words. So, I am just wondering if anyone could please help me out fix my code, and I am just wondering how to count how many spaces(esp multiple spaces) in a string in Python. I found how to count spaces in Java, but not in Python. For testcase, I attached the pic.
Thanks in advance.
My implementation:
input_string = input()
splitter = input_string.split()
final = []
for i in range(0,len(splitter)):
for j in range(0,len(splitter[i])):
if(j==0):
final.append(splitter[i][j].upper())
else:
final.append(splitter[i][j])
# Assumed that there is one space btw each words
final.append(' ')
print(''.join(final))
For Test case pic,
You can fix it by splitting with pattern ' ' (whitespace)
splitter = input_string.split(' ')
You can also use .capitalize() method instead of splitting the token again
s = "hello world 4lol"
a = s.split(' ')
new_string = ''
for i in range(0, len(a)) :
new_string = a[i].capitalize() if len(new_string)==0 else new_string +' '+ a[i].capitalize()
print(new_string)
Output:
Hello World 4lol
For counting number of spaces between two words, you can use python's regular expressions module.
import re
s = "hello world loL"
tokens = re.findall('\s+', s)
for i in range(0, len(tokens)) :
print(len(tokens[i]))
Output :
7
2
What I suggest doing for the tutorial question is a quick simple solution.
s = input()
print(s.title())
str.title() will capitalise the starting letter of every word in a string.
Now to answer the question for counting spaces you can use str.count()) which will take a string and return the number of occurrences it finds.
s = 'Hello World'
s.count(' ')
There are various other methods as well, such as:
s = input()
print(len(s) - len(''.join(s.split())))
s2 = input()
print(len(s2) - len(s2.replace(' ', '')))
However count is easiest to implement and follow.
Now, count will return the total number, if you're after the number of spaces between each world.
Then something like this should suffice
s = input()
spaces = []
counter = 0
for char in s:
if char== ' ':
counter += 1
elif counter != 0:
spaces.append(counter)
counter = 0
print(spaces)
import re
line = "Hello World LoL"
total = 0
for spl in re.findall('\s+', line):
print len(spl)
total += len(spl) # 4, 2
print total # 6
>>> 4
>>> 2
>>> 6
For you problem with spaces
my_string = "hello world"
spaces = 0
for elem in my_string:
if elem == " ":
#space between quotes
spaces += 1
print(spaces)
you can use count() function to count repeat of a special character
string_name.count('character')
for count space you should :
input_string = input()
splitter = input_string.split()
final = []
for i in range(0, len(splitter)):
for j in range(0, len(splitter[i])):
if(j==0):
final.append(splitter[i][j].upper())
else:
final.append(splitter[i][j])
final.append(' ')
count = input_string.count(' ')
print(''.join(final))
print (count)
good luck
I solved that problem a time ago, just add " " (white space) to the split function and then print each element separated by a white space. Thats all.
for i in input().split(" "):
print(i.capitalize(), end=" ")
The result of the split function with "hello world lol" is
>>> "hello world lol".split(" ")
>>>['hello', '', '', '', 'world', '', '', '', 'lol']
Then print each element + a white space.
Forget the spaces they are not your problem.
You can reduce the string to just the words without the extra spaces using split(None) which will give you a word count and your string i.e.
>>> a = " hello world lol"
>>> b = a.split(None)
>>> len(b)
3
>>> print(" ".join(b))
hello world lol
Edit: After following your link to read the actual question, next time include the relevant details in your question, it makes it easier all round,
your issue still isn't counting the number of spaces, before, between or after the words. The answer that solves the specific task has already been provided, in the form of:
>>> a= " hello world 42 lol"
>>> a.title()
' Hello World 42 Lol'
>>>
See the answer provided by #Steven Summers
Approach
Given a string, the task is to count the number of spaces between words in a string.
Example:
Input: "my name is geeks for geeks"
Output: Spaces b/w "my" and "name": 1
Spaces b/w "name" and "is": 2
Spaces b/w "is" and "geeks": 1
Spaces b/w "geeks" and "for": 1
Spaces b/w "for" and "geeks": 1
Input: "heyall"
Output: No spaces
Steps to be performed
Input string from the user’s and strip the string for the removing unused spaces.
Initialize an empty list
Run a for loop from 0 till the length of the string
Inside for loop, store all the words without spaces
Again Inside for loop, for storing the actual Indexes of the words.
Outside for loop, print the number of spaces b/w words.
Below is the implementation of the above approach:
# Function to find spaces b/w each words
def Spaces(Test_string):
Test_list = [] # Empty list
# Remove all the spaces and append them in a list
for i in range(len(Test_string)):
if Test_string[i] != "":
Test_list.append(Test_string[i])
Test_list1=Test_list[:]
# Append the exact position of the words in a Test_String
for j in range(len(Test_list)):
Test_list[j] = Test_string.index(Test_list[j])
Test_string[j] = None
# Finally loop for printing the spaces b/w each words.
for i in range(len(Test_list)):
if i+1 < len(Test_list):
print(
f"Spaces b/w \"{Test_list1[i]}\" and \"{Test_list1[i+1]}\": {Test_list[i+1]-Test_list[i]}")
# Driver function
if __name__ == "__main__":
Test_string = input("Enter a String: ").strip() # Taking string as input
Test_string = Test_string.split(" ") # Create string into list
if len(Test_string)==1:
print("No Spaces")
else:
Spaces(Test_string) # Call function

Why can't I return the modified str_func function back to the main function?

I have gotten about 80% of this program done but I cannot for the life of me figure out how to replace the vowels with asterisks and print the new string.
Instructions are as follows:
prompt the user to enter his/her first name.
output the number of letters in the name.
print all of the letters in the name separated by a space, all on one line.
print the name in all upper case.
use one slicing to make a new string from the name, but without the first and last letters.
print this new string.
pass the original name to a function named str_func.
inside the str_func function:
replace the vowels in the name with asterisks
return the modified name back to main
back in main, print the string returned by str_func.
My code so far:
def main():
name = input('Enter your first name: ')
print(name)
### print name with spaces in between characters
spaces = ''
for ch in name:
spaces = spaces + ch + ' '
print(spaces[:-1]) # to get rid of space after e
print('name in caps is,',name.upper()) # print name in all caps
print('After chopping the name we get',name[1:4])
print(str_func)
def str_func():
str_func = name.replace('a','*')
return str_func
main()
A friend of mine has helped somewhat stating I have issues with my str_func function:
The function is supposed to take the name as an argument in the main function when you call it.
You don't print it. You call it, something like this:
new_name = str_func(name)
Define str_func() like this. I put in some pseudocode for you.
def str_func(name):
###make a string containing the vowels
###loop through the name
###replace vowel if found with *
### after loop, return the name
Please help!!
This may help you.
import re
def main():
#Using "raw_input" instead of "input"
name = raw_input('Enter your first name: ')
print(name)
### print name with spaces in between characters
spaces = ''
for ch in name:
spaces = spaces + ch + ' '
print(spaces[:-1]) # to get rid of space after e
print('name in caps is,',name.upper()) # print name in all caps
print('After chopping the name we get',name[1:4])
new_name=str_func(name)
print(new_name)
def str_func(value):
#re is regular expression module. It will match string "Guido" and re.IGNORECASE makes it case insensitive.
#When value will Guido, it will be returned as it is.
if re.match(r"Guido",value,re.IGNORECASE):
return value
else:
for x in "aeiou":
value= value.replace(x, '*')
return value
main()
Output
C:\Users\Dinesh Pundkar\Desktop>python a.py
Enter your first name: Guido
Guido
G u i d o
('name in caps is,', 'GUIDO')
('After chopping the name we get', 'uid')
Guido
C:\Users\Dinesh Pundkar\Desktop>python a.py
Enter your first name: Jfalcone
Jfalcone
J f a l c o n e
('name in caps is,', 'JFALCONE')
('After chopping the name we get', 'fal')
Jf*lc*n*
C:\Users\Dinesh Pundkar\Desktop>
Others have provided a solution to your immediate problem but I’ll try to improve the whole code. I don't know what functions you've been introduced to so I might provide both a naive and a pythonic implementation for each steps.
To start with, you did not answered question 2: print the length of the input string. You can either count them manually:
size = 0
for letter in name:
size += 1
print(size)
or use the built-in function len:
size = len(name)
print(size) # or print(len(name)) if you don't need the intermediate variable
You can improve the spacing of your input using the join method of strings:
spaced = ' '.join(name)
print(spaced) # or print(' '.join(name)) if you don't need spaced
You can pass any iterable of strings to join and a string fits.
Your slicing take the second, third and fourth letter of your input. No matter what its length is. You need to either make use of the lenght of the string computed earlier:
sliced = name[1:size-1]
print(sliced)
or use negative numbers in the slice notation to count from the end of the string:
print(name[1:-1])
You're required to write a function and call it to mutate the string. You’ll thus have to call it like:
mutated = str_func(name)
print(mutated)
The function can either iterate over the original string:
def str_func(original):
copy = ''
for letter in original:
if letter in 'auieoy':
copy += '*'
else:
copy += letter
return copy
or use replace:
def str_func(original):
copy = original
for vowel in 'aeuioy':
copy = copy.replace(vowel, '*')
return copy
You can even use translate which can be a better fit in a more general use:
def str_func(original):
from string import maketrans
vowels = 'auieoy'
return original.translate(maketrans(vowels, '*' * len(vowels)))
Assembling all that together:
from string import maketrans
def do_stuff():
name = input('Enter your first name: ')
print('Your input is', name)
print('It\'s length is', len(name))
print('Adding spaces:', ' '.join(name))
print('Capitalizing it:', name.upper())
print('Chopping it:', name[1:-1])
mutated = str_func(name)
print('Removing vowels:', mutated)
def str_func(original):
vowels = 'auieoy'
return original.translate(maketrans(vowels, '*' * len(vowels)))
if __name__ == '__main__':
do_stuff()
test = 'qwertyuiopasdfghjklzxcvbnm'
def changestring(string):
for x in 'aeiou':
string = string.replace(x, '*')
return string
changestring(test)
'qw*rty***p*sdfghjklzxcvbnm'
Is this what you are trying to do?

Capitalized Word Function

I Am writing a function that should take a string input and return the string with every first letter of every word as a capital letter, I have achieved this to a certain degree.
My Code:
string = input("Please Enter A string:")
def capitalize_words(string):
split = string.split()
letter1 = ''
letter2 = ''
letter3 = ''
str1 = split[0]
str2 = split[1]
str3 = split[2]
for i in str1:
if i in str1[0]:
first = i.upper()
else:
letter1 = letter1 + i
string1 = (first+letter1)
for i in str2:
if i in str2[0]:
first = i.upper()
else:
letter2 = letter2 + i
string2 = (first+letter2)
for i in str3:
if i in str3[0]:
first = i.upper()
else:
letter3 = letter3 + i
string3 = (first+letter3)
result = string1+' '+string2+' '+string3
return result
func = capitalize_words(string)
print(func)
Input:
Please Enter A string:herp derp sherp
Output:
Herp Derp Sherp
However this is very inflexible because i can only enter 3 words with spaces no more no less , this makes for a rather primal program. I would like to be able to enter anything and get the desired result of the first letter of every word being a capital letter no matter how many words i enter.
I fear with my skills this is as far as I am able to get, can you please improve my program if possible.
>>> print(raw_input('Please Enter A string: ').title())
Please Enter A string: herp derp sherp
Herp Derp Sherp
Use str.title() to achieve what you want in one go.
But to process words in a sentence, use a loop instead of a series of local variables; here is a version that does the same what you are doing for an arbitrary number of words:
for i, word in enumerate(split):
split[i] = word[0].upper() + word[1:]
result = ' '.join(split)
I used string slicing as well to select just the first character, and all but the first character of a word. Note the use of enumerate() to give us a counter which wich we can replace words in the split list directly.
An alternative method is to use re.sub such as:
re.sub(r'\b.', lambda c: c.group().upper(), 'herp derp sherp and co.')
# 'Herp Derp Sherp And Co.'
You could write this in a one-line generator expression:
def upper_case(text):
return ' '.join(w[0].upper() + w[1:] for w in text.split())
Notice, that this function fails on single letter words and replaces any whitespace by a single space character.
Use this as
In [1]: upper_case(input('Please Enter A string: '))
Please Enter A string: hello world
Out[1]: 'Hello World'

Categories