Python separation by space - python

n = int(input("Give a number: "))
word = str(input("Give a word: "))
print(word.upper()*n)
n = 4
word = apple
output should be:
APPLE APPLE APPLE APPLE
now my problem is:
my output is APPLEAPPLEAPPLEAPPLE and I don't know how to put spaces between them.
I can't use split tho.
Thanks for the help.

Create a list of word.upper() and join its elements by separating them with a space:
lst = [word.upper()] * n
print(' '.join(lst))

print(' '.join([word]*n))
Expalanation:
[word] - a list of single word
[word]*n - a list of n elements, each element of list is word
Python string method join() returns a string in which the string elements of sequence have been joined by str separator.
https://www.tutorialspoint.com/python/string_join.htm

Just replace print(word.upper()*n) with print((word.upper() + " ")*n)

Related

Find the occurrence of a particular word from a file in python [duplicate]

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

Using itertools in python to create a wordlist, How can I make it work on a list of words instead of the current hardcoded word_list[0]?

char = input("Enter Char's to Combine with the Keyword: ")
n = int(input("Number of Char's Added to Keyword (2-9) :"))
letters = itertools.product(char,repeat=int(n))
for i in letters:
wrdLst.append(word_list[0] + "".join(i) + '\n')
save(wrdLst)
I'm using Itertools to create a wordlist using a baseword set by the user, word_list[0] .It currently works but I'd like to be able to perform the same thing on the entire list of items and not just word_list[0]
Pretty obvious, isn't it?
for word in word_list:
for i in letters:
wrdLst.append( word + ''.join(i) )
You should add the newline when you write it, not in the list.
What's the point of this? Your list will get very large very quickly and isn't very useful. With an 8 letter word and n=8, you're already at 16 million variations per word.

How to print a string by printing letter by letter and in reverse in python

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.

How to change the following output into a proper string?

I'm trying to code a chatbot that will print a string containing n times the first letter of my name, followed by "n" and then followed by n-1 times the second letter in my name.
Example:
name: chris
n = 5 (since there are 5 letters in the name)
n-1 = 4
first letter of the name: c
second letter of the name: h
The string I want to generate: ccccc5hhhh
My problem: The string generated is in brackets which I don't want. I want the string to be exactly as "ccccc5hhhh", no spaces; all in one line, but I keep getting ['c','c','c','c','c']5['h','h','h','h'] as the output.
st1 = input("First name? ==> ")
print("Please enter the first letter of your name")
letter = input ("First letter? ==>? ")
if (letter == st1[0]):
# initializing list of lists
test_list = st1[0]
test_list1 = st1[1]
# repeat letters n times
res = [ele for ele in test_list for i in range(len(st1))]
res2 = [ele for ele in test_list1 for i in range(len(st1)-1)]
# printing result
print(str(res), len(st1), str(res2))
You are looking for the join function. Using , with your arguments will insert a space though.
To get the result you are looking for you will want:
print(''.join(res) + str(len(st1)) + ''.join(res2))
Instead of converting your lists into string you can use the .join() function, like so ''.join(res)
So you final line should be:
print(''.join(res) + str(len(st1)) + ''.join(res2))
You're overcomplicating this. Just use string multiplication.
s = 'chris'
n = len(s)
res1 = s[0] * n
res2 = s[1] * (n - 1)
print(res1 + str(n) + res2) # -> ccccc5hhhh

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

Categories