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
Related
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
I'm trying to find the number of occurrences of a word in a string.
word = "dog"
str1 = "the dogs barked"
I used the following to count the occurrences:
count = str1.count(word)
The issue is I want an exact match. So the count for this sentence would be 0.
Is that possible?
If you're going for efficiency:
import re
count = sum(1 for _ in re.finditer(r'\b%s\b' % re.escape(word), input_string))
This doesn't need to create any intermediate lists (unlike split()) and thus will work efficiently for large input_string values.
It also has the benefit of working correctly with punctuation - it will properly return 1 as the count for the phrase "Mike saw a dog." (whereas an argumentless split() would not). It uses the \b regex flag, which matches on word boundaries (transitions between \w a.k.a [a-zA-Z0-9_] and anything else).
If you need to worry about languages beyond the ASCII character set, you may need to adjust the regex to properly match non-word characters in those languages, but for many applications this would be an overcomplication, and in many other cases setting the unicode and/or locale flags for the regex would suffice.
You can use str.split() to convert the sentence to a list of words:
a = 'the dogs barked'.split()
This will create the list:
['the', 'dogs', 'barked']
You can then count the number of exact occurrences using list.count():
a.count('dog') # 0
a.count('dogs') # 1
If it needs to work with punctuation, you can use regular expressions. For example:
import re
a = re.split(r'\W', 'the dogs barked.')
a.count('dogs') # 1
Use a list comprehension:
>>> word = "dog"
>>> str1 = "the dogs barked"
>>> sum(i == word for word in str1.split())
0
>>> word = 'dog'
>>> str1 = 'the dog barked'
>>> sum(i == word for word in str1.split())
1
split() returns a list of all the words in a sentence. Then we use a list comprehension to count how many times the word appears in a sentence.
import re
word = "dog"
str = "the dogs barked"
print len(re.findall(word, str))
You need to split the sentence into words. For you example you can do that with just
words = str1.split()
But for real word usage you need something more advanced that also handles punctuation. For most western languages you can get away with replacing all punctuation with spaces before doing str1.split().
This will work for English as well in simple cases, but note that "I'm" will be split into two words: "I" and "m", and it should in fact be split into "I" and "am". But this may be overkill for this application.
For other cases such as Asian language, or actual real world usage of English, you might want to use a library that does the word splitting for you.
Then you have a list of words, and you can do
count = words.count(word)
#counting the number of words in the text
def count_word(text,word):
"""
Function that takes the text and split it into word
and counts the number of occurence of that word
input: text and word
output: number of times the word appears
"""
answer = text.split(" ")
count = 0
for occurence in answer:
if word == occurence:
count = count + 1
return count
sentence = "To be a programmer you need to have a sharp thinking brain"
word_count = "a"
print(sentence.split(" "))
print(count_word(sentence,word_count))
#output
>>> %Run test.py
['To', 'be', 'a', 'programmer', 'you', 'need', 'to', 'have', 'a', 'sharp', 'thinking', 'brain']
2
>>>
Create the function that takes two inputs which are sentence of text and word.
Split the text of a sentence into the segment of words in a list,
Then check whether the word to be counted exist in the segmented words and count the occurrence as a return of the function.
If you don't need RegularExpression then you can do this neat trick.
word = " is " #Add space at trailing and leading sides.
input_string = "This is some random text and this is str which is mutable"
print("Word count : ",input_string.count(word))
Output -- Word count : 3
Below is a simple example where we can replace the desired word with the new word and also for desired number of occurrences:
import string
def censor(text, word):<br>
newString = text.replace(word,"+" * len(word),text.count(word))
print newString
print censor("hey hey hey","hey")
output will be : +++ +++ +++
The first Parameter in function is search_string.
Second one is new_string which is going to replace your search_string.
Third and last is number of occurrences .
Let us consider the example s = "suvotisuvojitsuvo".
If you want to count no of distinct count "suvo" and "suvojit" then you use the count() method... count distinct i.e) you don't count the suvojit to suvo.. only count the lonely "suvo".
suvocount = s.count("suvo") // #output: 3
suvojitcount = s.count("suvojit") //# output : 1
Then find the lonely suvo count you have to negate from the suvojit count.
lonelysuvo = suvocount - suvojicount //# output: 3-1 -> 2
This would be my solution with help of the comments:
word = str(input("type the french word chiens in english:"))
str1 = "dogs"
times = int(str1.count(word))
if times >= 1:
print ("dogs is correct")
else:
print ("your wrong")
If you want to find the exact number of occurrence of the specific word in the sting and you don't want to use any count function, then you can use the following method.
text = input("Please enter the statement you want to check: ")
word = input("Please enter the word you want to check in the statement: ")
# n is the starting point to find the word, and it's 0 cause you want to start from the very beginning of the string.
n = 0
# position_word is the starting Index of the word in the string
position_word = 0
num_occurrence = 0
if word.upper() in text.upper():
while position_word != -1:
position_word = text.upper().find(word.upper(), n, len(text))
# increasing the value of the stating point for search to find the next word
n = (position_word + 1)
# statement.find("word", start, end) returns -1 if the word is not present in the given statement.
if position_word != -1:
num_occurrence += 1
print (f"{word.title()} is present {num_occurrence} times in the provided statement.")
else:
print (f"{word.title()} is not present in the provided statement.")
This is simple python program using split function
str = 'apple mango apple orange orange apple guava orange'
print("\n My string ==> "+ str +"\n")
str = str.split()
str2=[]
for i in str:
if i not in str2:
str2.append(i)
print( i,str.count(i))
I have just started out to learn coding in general and I do not know any libraries as such.
s = "the dogs barked"
value = 0
x = 0
y=3
for alphabet in s:
if (s[x:y]) == "dog":
value = value+1
x+=1
y+=1
print ("number of dog in the sentence is : ", value)
Another way to do this is by tokenizing string (breaking into words)
Use Counter from collection module of Python Standard Library
from collections import Counter
str1 = "the dogs barked"
stringTokenDict = { key : value for key, value in Counter(str1.split()).items() }
print(stringTokenDict['dogs'])
#This dictionary contains all words & their respective count
I want to print a string in reverse and build it by printing letter by letter.
E.g - Word is: string
Ideal output is:
g
gn
gni
gnir
gnirt
gnirts
I want the user to be able to enter any word not just "String"
Code I have tried:
text = input('Enter a string: ')
reversed_text = ''
last_index = len(text) - 1
for i in range(last_index, -1, -5):
for i in range(last_index, -1, -1):
for i in range(last_index, -1, -1):
reversed_text += text[i]
print(reversed_text)
s=input("Word: ")
r=''
for char in reversed(s):
r+=char
print(r)
print ("Reversed word is %s " % (r))
This is the code I used, it works thank you for the answers
s='string'
r=''
for char in reversed(s):
r+=char
print(r)
This code does what you're asking.
A simple way of doing this with user input should be something on these lines:
newstring = ""
enterString = (str(input("Enter a string to be reversed:")))
count = 0
for i in reversed(enterString):
newstring += i
count += 1
print ("Reversed string %s is this: %s" % (count, newstring))
Output with count of how many times till it gets the last character:
Enter a string to be reversed:hello
Reversed string 1 is this: o
Reversed string 2 is this: ol
Reversed string 3 is this: oll
Reversed string 4 is this: olle
Reversed string 5 is this: olleh
This solution uses extended slice to reverse the word segments and separate each with a space. Other answers have separated the reversed word segments with a newline. Just replace ' '.join with '\n'.join if you require this behavior.
word = 'string'
reversed = '\n'.join(word[-1:i:-1] for i in range(-2, -2 - len(word), -1))
print(reversed)
edit: Separated reversed word segments with newline to reflect updated question.
So I have, p.e, this string: ' I love python ' and I want to convert all the spaces to '_'. My problem is that I also need to delete the outside spaces so I dont finish with the result: '_I_love_python__' and more like this 'I_love_python'
I searched and found out that I can develop it with a single line of code mystring.strip().replace(" ", "_") which is unfortunaly is sintax that I cant apply in my essay.
So what I landed with was this:
frase= str(input('Introduza: '))
aux=''
for car in frase:
if car==' ':
car='_'
aux+=car
else:
aux+=car
print(aux)
My problem now is on deleting those outside spaces. What I thought about was runing another for i in in the start and another on the final of the string and to stop until they found a non space caracter. But unfortunaly I havent been able to do that...
Apreciate all the help you can suply!
I came up with following solution:
You iterate over the string, but instead of replacing the space with underscore as soon as it appears, you store the amount of spaces encountered. Then, once a non-space-character is reached, you add the amount of spaces found to the string. So if the string ends with lots of spaces, it will never reach a non-space-character and therefore never add the underscores.
For cutting off the spaces at the beginning, I just added a condition to add the underscores being: "Have I encountered a non-space-character before?"
Here is the code:
text = " I love python e "
out = ""
string_started = False
underscores_to_add = 0
for c in text:
if c == " ":
underscores_to_add += 1
else:
if string_started:
out += "_" * underscores_to_add
underscores_to_add = 0
string_started = True
out += c
print(out) # prints "I_love___python____e"
You can use the following trick to remove leading and trailing spaces in your string:
s = ' I love python '
ind1 = min(len(s) if c == ' ' else n for n, c in enumerate(s))
ind2 = max(0 if c == ' ' else n for n, c in enumerate(s))
s = ''.join('_' if c == ' ' else c for c in s[ind1:ind2 + 1])
print('*', s, '*', sep='')
Output:
*I_love_python*
If you are not allowed to use strip() method
def find(text):
for i, s in enumerate(text):
if s != " ":
break
return i
text = " I love python e "
text[find(text):len(text)-find(text[::-1])].replace(" ","_")
texts = [" I love python e ","I love python e"," I love python e","I love python e ", "I love python e"]
for text in texts:
print (text[find(text):len(text)-find(text[::-1])].replace(" ","_"))
output:
I_love___python____e
I_love___python____e
I_love___python____e
I_love___python____e
I_love___python____e
Given a string find will find the first non space character in the string
Use find to find the first nonspace character and the last nonspace character
Get the substring using above found indices
Replace all spaces with _ in the above substring
Define a function called print_skip that accepts a string and prints out every second word in the string, starting with the first word. A word is treated as any sequence of letters that is separated from other letters by white space. You may assume a string is passed as a parameter.
thats the problem i'm having.
i tried to put it in a a list and index it from there and it works fine and passed most of the test that the website gives except one.
print_skip('Hello world!\nHow\nare\nyou!') and the excepted output is Hello How you. my code just crash when this happens
def print_skip(text):
only_letters = ''
new_words = []
for c in text:
if(c.isalpha() or c==' '):
only_letters += c
for x in only_letters.split():
new_words.append(x)
for i in range(0,len(new_words)+1,2):
print(new_words[i])
testing error
my code so far
this is the original question
So strings in python actually let you index them like a list. Here's an example:
>>> myString = "How are You? Where are you from?"
>>> breakUp = myString.split()
>>> breakUp[::2] #This 2 represents step size, so ever 2nd word will be called.
['How', 'You?', 'are', 'from?']
Notice this includes the first word.
Appendum: So just using the split() here is not enough. I looked at the above example and the escape characters are in the string. I think a viable solution to dealing with escape characters inside your string are just replacting them with a ''. Here is an example:
myFixedString = "'Hello world!\nHow\nare\nyou!".replace('\n', ' ')
printSkip(myFixedString)
Solution using for loop and modulo:
sentence = '1 2 3 4 5 6 7\n8 9 10'
words = sentence.split()
for i in range(len(words)):
if i % 2 == 1: # is true on uneven numbers, e.g. index 1, index 3, index 5
print(words[i])
>>>2
>>>4
>>>6
>>>8
>>>10
This can be refactored down to a list comprehension as follow:
sentence = '1 2 3 4 5 6 7\n8 9 10'
words = sentence.split()
[print(words[i]) if i % 2 == 1 else None for i in range(len(words))]
You could use regex and re.sub to remove all non-alphabetic characters for each odd word in the string.
import re
def print_skip(text):
if not text:
return
regex = re.compile('[^a-zA-Z]')
for index, word in enumerate(text.split()):
if index % 2 == 0:
print(regex.sub('', word))
Method without using regex:
def print_skip(text):
words = text.split()
for index, word in enumerate(words):
if not word.isalpha():
clean_word = ''
for i in range(len(word)):
if word[i].isalpha():
clean_word += word[i]
words[index] = clean_word
if index % 2 == 0:
print(words[index])