Write a function that accepts a string of words separated by spaces
consisting of alphabetic characters and returns a string such that
each word in the input string is reversed while the order of the words
in the input string is preserved. Capitalization does matter here. The
length of the input string must be equal to the length of the output
string i.e. there should be no trailing or leading spaces in your
output string. For example if:
input_string = “this is a sample test”
then the function should return a string such as:
"siht si a elpmas tset"
This is my code:
def preserve_and_reverse (input_str):
list = input_str.split()
print (list)
reverse_character = ""
for i in range (0, len(input_str)):
split_list = list[0:(i + 1)]
print (split_list)
for j in split_list_advance:
reverse_character = reverse_character + split_list[j]
output_str = output_str.append(reverse_character)
output = output_str.replace("", " ")
print (output)
#Main Program
input_str = input("Enter a string: ")
result = preserve_and_reverse (input_str)
print (result)
I am not getting anywhere with the code. Should I try a different approach like traverse each character and when I encounter a white-space just slice the string and then perform a reverse?
Any help would be appreciated.
Split over spaces, reverse each string through map with [::-1] then join them back with ' '.join
>>> s = 'this is a sample test'
>>>
>>> ' '.join(map(lambda s:s[::-1], s.split()))
'siht si a elpmas tset'
This is how I would have done it:
def preserve_and_reverse(input_str):
# Split the String into an Array
list_ = input_str.split(" ")
return_str = ""
# For Each String in the Array
for item in list_:
# Add Reversed String to Return String
return_str += item[::-1] + " "
# Return String without leading/trailing spaces
return return_str.strip()
# Main Program
string_input = input("Enter a string: ")
result = preserve_and_reverse(string_input.strip())
print(result)
Something like this will do (step-by-step):
input_string = "this is a sample test"
words = input_string.split()
nwords = []
for i in words:
rword = ""
for c in reversed(word):
rword += c
nwords.append(rword)
output_string = " ".join(nwords)
print(output_string)
Result:
siht si a elpmas tset
Step by step explanation:
You split your input text into list of string:
words = input_string.split()
You iterate over the words
for word in words):
For each word, you prepare a reversed word rword and build up the reversed word by adding up character from the old word but reversed:
rword = ""
for c in reversed(word):
rword += c
nwords.append(rword)
you rejoin the reversed words - but in order and print it:
output_string = " ".join(nwords)
print(output_string)
Or, more simply:
input_string = "this is a sample test"
words = input_string.split()
output_string = ""
for word in words:
for c in reversed(word):
output_string += c
output_string += " "
print(output_string)
word[::-1] reverses the order of the string variable named word which is obtained by iterating through each split word in the sentence.
>>> ' '.join(word[::-1] for word in input_string.split())
'siht si a elpmas tset'
Step by step:
>>> input_string.split()
['this', 'is', 'a', 'sample', 'test']
>>> [word[::-1] for word in input_string.split()]
['siht', 'si', 'a', 'elpmas', 'tset']
>>> ' '.join(word[::-1] for word in input_string.split())
'siht si a elpmas tset'
All of the other answers so far ignore what happens when extra spaces are between words or at either end of the input string. Please test your code to verify that is works properly. The main function provided below has a few tests that you may want to use to verify your function is working properly, and you may want to add more tests if you find that your code is not behaving correctly:
def main():
print('Running test 1 ...')
text = 'this is a sample test'
par = preserve_and_reverse(text)
assert par == 'siht si a elpmas tset'
print('Running test 2 ...')
text = 'This is a sample TEST'
par = preserve_and_reverse(text)
assert par == 'sihT si a elpmas TSET'
print('Running test 3 ...')
text = 'This string has some extra spaces'
par = preserve_and_reverse(text)
assert par == 'sihT gnirts sah emos artxe secaps'
print('Running test 4 ...')
text = ' check spaces at string ends '
par = preserve_and_reverse(text)
assert par == ' kcehc secaps ta gnirts sdne '
print('Done!')
def preserve_and_reverse(text):
return ' '.join(word[::-1] for word in text.split(' '))
if __name__ == '__main__':
main()
def sample(string):
list=[]
string1=string.split()
for i in string1:
list.append(i[::-1])
print(" ".join(list))
if __name__=="__main__":
input=input("Enter string: ")
sample(input)
Related
For this problem, I am given strings ThatAreLikeThis where there are no spaces between words and the 1st letter of each word is capitalized. My task is to lowercase each capital letter and add spaces between words. The following is my code. What I'm doing there is using a while loop nested inside a for-loop. I've turned the string into a list and check if the capital letter is the 1st letter or not. If so, all I do is make the letter lowercase and if it isn't the first letter, I do the same thing but insert a space before it.
def amendTheSentence(s):
s_list = list(s)
for i in range(len(s_list)):
while(s_list[i].isupper()):
if (i == 0):
s_list[i].lower()
else:
s_list.insert(i-1, " ")
s_list[i].lower()
return ''.join(s_list)
However, for the test case, this is the behavior:
Input: s: "CodesignalIsAwesome"
Output: undefined
Expected Output: "codesignal is awesome"
Console Output: Empty
You can use re.sub for this:
re.sub(r'(?<!\b)([A-Z])', ' \\1', s)
Code:
import re
def amendTheSentence(s):
return re.sub(r'(?<!\b)([A-Z])', ' \\1', s).lower()
On run:
>>> amendTheSentence('GoForPhone')
go for phone
Try this:
def amendTheSentence(s):
start = 0
string = ""
for i in range(1, len(s)):
if s[i].isupper():
string += (s[start:i] + " ")
start = i
string += s[start:]
return string.lower()
print(amendTheSentence("CodesignalIsAwesome"))
print(amendTheSentence("ThatAreLikeThis"))
Output:
codesignal is awesome
that are like this
def amendTheSentence(s):
new_sentence=''
for char in s:
if char.isupper():
new_sentence=new_sentence + ' ' + char.lower()
else:
new_sentence=new_sentence + char
return new_sentence
new_sentence=amendTheSentence("CodesignalIsAwesome")
print (new_sentence)
result is codesignal is awesome
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
What are other ways to split a string without using the split() method? For example, how could ['This is a Sentence'] be split into ['This', 'is', 'a', 'Sentence'] without the use of the split() method?
sentence = 'This is a sentence'
split_value = []
tmp = ''
for c in sentence:
if c == ' ':
split_value.append(tmp)
tmp = ''
else:
tmp += c
if tmp:
split_value.append(tmp)
You can use regular expressions if you want:
>>> import re
>>> s = 'This is a Sentence'
>>> re.findall(r'\S+', s)
['This', 'is', 'a', 'Sentence']
The \S represents any character that isn't whitespace, and the + says to find one or more of those characters in a row. re.findall will create a list of all strings that match that pattern.
But, really, s.split() is the best way to do it.
A recursive version, breaking out the steps in detail:
def my_split(s, sep=' '):
s = s.lstrip(sep)
if sep in s:
pos = s.index(sep)
found = s[:pos]
remainder = my_split(s[pos+1:])
remainder.insert(0, found)
return remainder
else:
return [s]
print my_split("This is a sentence")
Or, the short, one-line form:
def my_split(s, sep=' '):
return [s[:s.index(sep)]] + my_split(s[s.index(sep)+1:]) if sep in s else [s]
Starting with a list of strings, if you would like to split these strings there are a couple ways to do so depending on what your desired output is.
Case 1: One list of strings (old_list) split into one new list of strings (new_list).
For example ['This is a Sentence', 'Also a sentence'] -> ['This', 'is', 'a', 'Sentence', 'Also', 'a', 'sentence'].
Steps:
Loop through the strings. for sentence in old_list:
Create a new string to keep track of the current word (word).
Loop through the characters in each of these strings. for ch in sentence:
If you come across the character(s) you want to split on (spaces in this example), check that word is not empty and add it to the new list, otherwise add the character to word.
Make sure to add word to the list after looping through all the characters.
The final code:
new_list = []
for sentence in old_list:
word = ''
for ch in sentence:
if ch == ' ' and word != '':
new_list.append(word)
word = ''
else:
word += ch
if word != '':
new_list.append(word)
This is equivalent to
new_list = []
for sentence in old_list:
new_list.extend(sentence.split(' '))
or even simpler
new_list = ' '.join(old_list).split(' ')
Case 2: One list of strings (old_list) split into a new list of lists of strings (new_list).
For example ['This is a Sentence', 'Also a sentence'] -> [['This', 'is', 'a', 'Sentence'], ['Also', 'a', 'sentence']].
Steps:
Loop through the strings. for sentence in old_list:
Create a new string to keep track of the current word (word) and a new list to keep track of the words in this string (sentence_list).
Loop through the characters in each of these strings. for ch in sentence:
If you come across the character(s) you want to split on (spaces in this example), check that word is not empty and add it to sentence_list, otherwise add the character to word.
Make sure to add word to sentence_list after looping through all the characters.
Append (not extend) sentence_list to the new list and move onto the next string.
The final code:
new_list = []
for sentence in old_list:
sentence_list = []
word = ''
for ch in sentence:
if ch == ' ' and word != '':
sentence_list.append(word)
word = ''
else:
word += ch
if word != '':
sentence_list.append(word)
new_list.append(sentence_list)
This is equivalent to
new_list = []
for sentence in old_list:
new_list.append(sentence.split(' '))
or using list comprehensions
new_list = [sentence.split(' ') for sentence in old_list]
This is simple code to split a char value from a string value; i.e
INPUT : UDDDUDUDU
s = [str(i) for i in input().strip()]
print(s)
OUTPUT: ['U','D','D','D','U','D','U','D','U']
sentence = 'This is a sentence'
word=""
for w in sentence :
if w.isalpha():
word=word+w
elif not w.isalpha():
print(word)
word=""
print(word)
string1 = 'bella ciao amigos'
split_list = []
tmp = ''
for s in string1:
if s == ' ':
split_list.append(tmp)
tmp = ''
else:
tmp += s
if tmp:
split_list.append(tmp)
print(split_list)
Output:
------> ['bella', 'ciao', 'amigos']
reverse_list = split_list[::-1]
print(reverse_list)
Output:
------> ['amigos', 'ciao', 'bella']
def mysplit(strng):
strng = strng.lstrip()
strng = strng.rstrip()
lst=[]
temp=''
for i in strng:
if i == ' ':
lst.append(temp)
temp = ''
else:
temp += i
if temp:
lst.append(temp)
return lst
print(mysplit("Hello World"))
print(mysplit(" "))
print(mysplit(" abc "))
print(mysplit(""))
This is one of the most accurate replicas of split method:
def splitter(x, y = ' '):
l = []
for i in range(x.count(y) + 1):
a = ''
for i in x:
if i == y: break
a += i
x = x[len(a) + 1 : len(x)]
l.append(a)
return ([i for i in l if i != ''])
my_str='This is a sentence'
split_value = []
tmp = ''
for i in my_str+' ':
if i == ' ':
split_value.append(tmp)
tmp = ''
else:
tmp += i
print(split_value)
Just a small modification to the code already given
I am having a small problem in my code. I am trying to reverse the words and the character of a string. For example "the dog ran" would become "ehT god nar"
The code almost works. It just does not add spaces. How would you do that?
def reverseEachWord(str):
reverseWord=""
list=str.split()
for word in list:
word=word[::-1]
reverseWord=reverseWord+word+""
return reverseWord
You are on the right track. The main issue is that "" is an empty string, not a space (and even if you fix this, you probably don't want a space after the final word).
Here is how you can do this more concisely:
>>> s='The dog ran'
>>> ' '.join(w[::-1] for w in s.split())
'ehT god nar'
def reversed_words(sequence):
return ' '.join(word[::-1] for word in sequence.split())
>>> s = "The dog ran"
>>> reversed_words(s)
... 'ehT god nar'
name=input('Enter first and last name:')
for n in name.split():
print(n[::-1],end=' ')
You can also deal with noise in the string using the re module:
>>> import re
>>> s = "The \n\tdog \t\nran"
>>> " ".join(w[::-1] for w in re.split(r"\s+", s))
'ehT god nar'
Or if you don't care:
>>> s = "The dog ran"
>>> re.sub(r"\w+", lambda w: w.group(0)[len(w.group(0))::-1], s)
'Teh god nar'
def reverse_words(sentence):
return " ".join((lambda x : [i[::-1] for i in x])(sentence.split(" ")))
Another way to go about it is by adding a space to your words reverseWord=reverseWord+word+" " and removing the space at the end of your output by using .strip()
def reverse_words(str):
reverseWord = ""
list = str.split()
for word in list:
word = word[::-1]
reverseWord = reverseWord + word + " "
return reverseWord.strip()
check out this post on how it's used
Here is a solution without using join / split :
def reverse(sentence):
answer = ''
temp = ''
for char in sentence:
if char != ' ':
temp += char
continue
rev = ''
for i in range(len(temp)):
rev += temp[len(temp)-i-1]
answer += rev + ' '
temp = ''
return answer + temp
reverse("This is a string to try")
Write a simple program that reads a line from the keyboard and outputs the same line where
every word is reversed. A word is defined as a continuous sequence of alphanumeric characters
or hyphen (‘-’). For instance, if the input is
“Can you help me!”
the output should be
“naC uoy pleh em!”
I just tryed with the following code, but there are some problem with it,
print"Enter the string:"
str1=raw_input()
print (' '.join((str1[::-1]).split(' ')[::-2]))
It prints "naC uoy pleh !em", just look the exclamation(!), it is the problem here. Anybody can help me???
The easiest is probably to use the re module to split the string:
import re
pattern = re.compile('(\W)')
string = raw_input('Enter the string: ')
print ''.join(x[::-1] for x in pattern.split(string))
When run, you get:
Enter the string: Can you help me!
naC uoy pleh em!
You could use re.sub() to find each word and reverse it:
In [8]: import re
In [9]: s = "Can you help me!"
In [10]: re.sub(r'[-\w]+', lambda w:w.group()[::-1], s)
Out[10]: 'naC uoy pleh em!'
My answer, more verbose though. It handles more than one punctuation mark at the end as well as punctuation marks within the sentence.
import string
import re
valid_punctuation = string.punctuation.replace('-', '')
word_pattern = re.compile(r'([\w|-]+)([' + valid_punctuation + ']*)$')
# reverses word. ignores punctuation at the end.
# assumes a single word (i.e. no spaces)
def word_reverse(w):
m = re.match(word_pattern, w)
return ''.join(reversed(m.groups(1)[0])) + m.groups(1)[1]
def sentence_reverse(s):
return ' '.join([word_reverse(w) for w in re.split(r'\s+', s)])
str1 = raw_input('Enter the sentence: ')
print sentence_reverse(str1)
Simple solution without using re module:
print 'Enter the string:'
string = raw_input()
line = word = ''
for char in string:
if char.isalnum() or char == '-':
word = char + word
else:
if word:
line += word
word = ''
line += char
print line + word
you can do this.
print"Enter the string:"
str1=raw_input()
print( ' '.join(str1[::-1].split(' ')[::-1]) )
or then, this
print(' '.join([w[::-1] for w in a.split(' ') ]))