Finding the index of a common character in a for loop - python

First of all I know this is probably a [duplicate] but I could not find the answer to my question specifically anywhere.
I have a string generated by the user that I want my program to iterate over. Everything goes fine except for the fact that because I'm trying to access the index of a character " " (space) which appears more than once, whenever I try getting the index of the newly assigned space value for " ", it automatically gives me the index of the first " " in the string. I want this program to differentiate between words and create a list with the words in the string using a space to distinguish between them. What am I doing wrong?
list_words=[]
def findwords(sentence):
index1=0
index2=0
for space in sentence:
if space==" ":
index1=sentence.index(space)
list_words.append(sentence[index2:index1])
index2=index1
print(list_words)
findwords("What is your name?")

If you want a list of words, then use the API that was designed for that purpose:
def findwords(sentence):
return sentence.split()
print(findwords("What is your name?"))

As #Tim Roberts mentioned, you can simply use sentence.split(" ") to retrieve a list of words in the sentence split by a space. This function creates a list that has elements as words of the sentence that are divided by a " ".
However, using your code, we can edit it so that after we find a space, we add the previous word to the list and we edit sentence so that it does not contain the previous word or space. After we reach the end of the sentence, since there is no space ending the sentence, after the for loop, we should add whatever word is left in our sentence to the list.
Remember to use a copy of sentence to iterate as we should not modify whatever we are iterating. This code is built off of your code and produces the same output as using sentence.split(" "):
list_words=[]
def findwords(sentence):
sent = sentence
for space in sent:
if space == " ":
index1=sentence.index(space)
list_words.append(sentence[0:index1 + 1])
sentence = sentence[index1 + 1:]
list_words.append(sentence)
findwords("What is your name?")
print(list_words)
Output:
['What ', 'is ', 'your ', 'name?']
I hope this helped answer your question! Let me know if you need any further details or clarification :)

Related

How to extract first letter of every nth word in a sentence?

I was trying to extract the first letter of every 5th word and after doing a bit of research I was able to figure out how to obtain every 5th word. But, how do I know extract the first letters of every 5th word and put them together to make a word out of them. This is my progress so far:
def extract(text):
for word in text.split()[::5]:
print(word)
extract("I like to jump on trees when I am bored")
As the comment pointed out, split it and then just access the first character:
def extract(text):
for word in text.split(" "):
print(word[0])
text.split(" ") returns an array and we are looping through that array. word is the current entry (string) in that array. Now, in python you can access the first character of a string in typical array notation. Therefore, word[0] returns the first character of that word, word[-1] would return the last character of that word.
I don't know how did you solve the first part and can not solve the second one,
but anyway, strings in python are simply a list of characters, so if you want to access the 1st character you get the 0th index. so applying that to your example, as the comment mentioned you type (word[0]),
so you can print the word[0] or maybe collect the 1st characters in a list to do any further operations (I do believe that what you want to do, not just printing them!)
def extract(text):
mychars=[]
for word in text.split()[::5]:
mychars.append(word[0])
print(mychars)
extract("I like to jump on trees when I am bored")
The below code might help you out. Just an example idea based on what you said.
#
# str Text : A string of words, such as a sentence.
# int split : Split the string every nth word
# int maxLen : Max number of chars extracted from beginning of each word
#
def extract(text,split,maxLen):
newWord = ""
# Every nth word
for word in text.split()[::split]:
if len(word) < maxLen:
newWord += word[0:] #Entire word (if maxLength is small)
else:
newWord += word[:maxLen] #Beginning of word until nth letter
return (None if newWord=="" else newWord)
text = "The quick brown fox jumps over the lazy dog."
result = extract(text, split=5, maxLen=2) #Use split=5, maxLen=1 to do what you said specifically
if (result):
print (result) #Expected output: "Thov"

how to skip a specific char in string(encrypted in a certain manner) message while printing the message in a specific format in python

In a certain encrypted message which has information about the location(area, city), the characters are jumbled such that first character of the first word is followed by the first character of the second word, then it is followed by the second character of the first word and so on
In other words, let’s say the location is bandra,mumbai
The encrypted message says ‘bmaunmdbraai’.
Sample Input:
bmaunmdbraai
Sample Output:
bandra,mumbai
Let’s say the size or length of the two words wouldn’t match then the smaller word is appended with # and then encrypted in the above format.
With this in mind write a code to identify the right location and print it as place,city.
input_str='dmeulmhbia#i'
message1=input_str[0::2]
message2=input_str[1::2]
print(message1+","+message2)
import ast,sys
input_str = sys.stdin.read()
message1 = input_str[0:-1:2]
message2 = input_str[1:len(input_str):2]
print(message1.strip('#') + "," + message2.strip('#'))
Using [::2], you can get every second character. Then just use rstrip('#') to remove the unwanted hashtag.
input_str='dmeulmhbia#i'
', '.join([input_str[::2].rstrip('#'), input_str[1::2].rstrip('#')])
Out[5]: 'bandra, mumbai'
Separated by ', ', I am concatenating every second letter, and also every second letter starting from the second letter, and remove # when it's detected at the end of either word.
input_str='dmeulmhbia#i'
message1=input_str[0::2].rstrip('#')
message2=input_str[1::2].rstrip('#')
print(message1+","+message2)
In addition to the above answers, you may use a loop to resolve the same.
import ast,sys
input_str = sys.stdin.read()
city=''
place=''
len_name=len(input_str)
for i in range(0,len_name) :
if i%2==0 :
city=city+input_str[i]
else :
`place=place+input_str[i]
message1=city.rstrip('#')
message2=place.rstrip('#')
print(message1+","+message2)

split strings with multiple special characters into lists without importing anything in python

i need to make a program that will capitalize the first word in a sentence and i want to be sure that all the special characters that are used to end a sentence can be used.
i can not import anything! this is for a class and i just want some examples to do this.
i have tried to use if to look in the list to see if it finds the matching character and do the correct split operatrion...
this is the function i have now... i know its not good at all as it just returns the original string...
def getSplit(userString):
userStringList = []
if "? " in userString:
userStringList=userString.split("? ")
elif "! " in userStringList:
userStringList = userString.split("! ")
elif ". " in userStringList:
userStringList = userString.split(". ")
else:
userStringList = userString
return userStringList
i want to be able to input something like this is a test. this is a test? this is definitely a test!
and get [this is a test.', 'this is a test?', 'this is definitely a test!']
and the this is going to send the list of sentences to another function to make the the first letter capitalized for each sentence.
this is an old homework assignment that i could only make it use one special character to separate the string into a list. buti want to user to be able to put in more then just one kind of sentence...
This may hep. use str.replace to replace special chars with space and the use str.split
Ex:
def getSplit(userString):
return userString.replace("!", " ").replace("?", " ").replace(".", " ").split()
print(map(lambda x:x.capitalize, getSplit("sdfsdf! sdfsdfdf? sdfsfdsf.sdfsdfsd!fdfgdfg?dsfdsfgf")))
Normally, you could use re.split(), but since you cannot import anything, the best option would be just to do a for loop. Here it is:
def getSplit(user_input):
n = len(user_input)
sentences =[]
previdx = 0
for i in range(n - 1):
if(user_input[i:i+2] in ['. ', '! ', '? ']):
sentences.append(user_input[previdx:i+2].capitalize())
previdx = i + 2
sentences.append(user_input[previdx:n].capitalize())
return "".join(sentences)
I would split the string at each white space. Then scan the list for words that contain the special character. If any is present, the next word is capitalised. Join the list back at the end. Of course, this assumes that there are no more than two consecutive spaces between words.
def capitalise(text):
words = text.split()
new_words = [words[0].capitalize()]
i = 1
while i < len(words) - 1:
new_words.append(words[i])
if "." in words[i] or "!" in words[i] or "?" in words[i]:
i += 1
new_words.append(words[i].capitalize())
i += 1
return " ".join(new_words)
If you can use the re module which is available by default in python, this is how you could do it:
import re
a = 'test this. and that, and maybe something else?even without space. or with multiple.\nor line breaks.'
print(re.sub(r'[.!?]\s*\w', lambda x: x.group(0).upper(), a))
Would lead to:
test this. And that, and maybe something else?Even without space. Or with multiple.\nOr line breaks.

Write programs that read a line of input as a string and print every second letter of the string in Python

Write programs that read a line of input as a string and print every second letter of the string in Python?
So far I have written:
string=input('Enter String: ')
for char in range(0,len(string),2):
print(len(char))
if i input a string: qwerty
it should print "qet"
You need to keep it much simpler than this. If you enter a word and are looking to slice it at a specific point, use slicing.
Your criteria: qwerty it should print "qet"
So, you are looking to print every second letter:
>>> a = "querty"
>>> a[::2]
'qet'
Slicing works like this:
[from start: from end: step]
So, in your case, you are looking to simply print every second, so you want to make use of your step. So, simply slice leaving the start and end empty, since you want to position yourself at the beginning of the string and then simply go every second. This is the reasoning behind using [::2]
Every second letter should start with index of 1 not 0. So, if your input is "qwerty", you output should be "wry".
Code below may be able to answer your question.
sentence = input("\nPlease enter a string : ")
print("Every second letter of the string " + sentence + " is ", end="")
for i in range(len(sentence)):
if i % 2 == 1:
print(sentence[i] + " ", end="")

How do I calculate the number of times a word occurs in a sentence?

So I've been learning Python for some months now and was wondering how I would go about writing a function that will count the number of times a word occurs in a sentence. I would appreciate if someone could please give me a step-by-step method for doing this.
Quick answer:
def count_occurrences(word, sentence):
return sentence.lower().split().count(word)
'some string.split() will split the string on whitespace (spaces, tabs and linefeeds) into a list of word-ish things. Then ['some', 'string'].count(item) returns the number of times item occurs in the list.
That doesn't handle removing punctuation. You could do that using string.maketrans and str.translate.
# Make collection of chars to keep (don't translate them)
import string
keep = string.lowercase + string.digits + string.whitespace
table = string.maketrans(keep, keep)
delete = ''.join(set(string.printable) - set(keep))
def count_occurrences(word, sentence):
return sentence.lower().translate(table, delete).split().count(word)
The key here is that we've constructed the string delete so that it contains all the ascii characters except letters, numbers and spaces. Then str.translate in this case takes a translation table that doesn't change the string, but also a string of chars to strip out.
wilberforce has the quick, correct answer, and I'll give the long winded 'how to get to that conclusion' answer.
First, here are some tools to get you started, and some questions you need to ask yourself.
You need to read the section on Sequence Types, in the python docs, because it is your best friend for solving this problem. Seriously, read it. Once you have read that, you should have some ideas. For example you can take a long string and break it up using the split() function. To be explicit:
mystring = "This sentence is a simple sentence."
result = mystring.split()
print result
print "The total number of words is: " + str(len(result))
print "The word 'sentence' occurs: " + str(result.count("sentence"))
Takes the input string and splits it on any whitespace, and will give you:
["This", "sentence", "is", "a", "simple", "sentence."]
The total number of words is 6
The word 'sentence' occurs: 1
Now note here that you do have the period still at the end of the second 'sentence'. This is a problem because 'sentence' is not the same as 'sentence.'. If you are going to go over your list and count words, you need to make sure that the strings are identical. You may need to find and remove some punctuation.
A naieve approach to this might be:
no_period_string = mystring.replace(".", " ")
print no_period_string
To get me a period-less sentence:
"This sentence is a simple sentence"
You also need to decide if your input going to be just a single sentence, or maybe a paragraph of text. If you have many sentences in your input, you might want to find a way to break them up into individual sentences, and find the periods (or question marks, or exclamation marks, or other punctuation that ends a sentence). Once you find out where in the string the 'sentence terminator' is you could maybe split up the string at that point, or something like that.
You should give this a try yourself - hopefully I've peppered in enough hints to get you to look at some specific functions in the documentation.
Simplest way:
def count_occurrences(word, sentence):
return sentence.count(word)
text=input("Enter your sentence:")
print("'the' appears", text.count("the"),"times")
simplest way to do it
Problem with using count() method is that it not always gives the correct number of occurrence when there is overlapping, for example
print('banana'.count('ana'))
output
1
but 'ana' occurs twice in 'banana'
To solve this issue, i used
def total_occurrence(string,word):
count = 0
tempsting = string
while(word in tempsting):
count +=1
tempsting = tempsting[tempsting.index(word)+1:]
return count
You can do it like this:
def countWord(word):
numWord = 0
for i in range(1, len(word)-1):
if word[i-1:i+3] == 'word':
numWord += 1
print 'Number of times "word" occurs is:', numWord
then calling the string:
countWord('wordetcetcetcetcetcetcetcword')
will return: Number of times "word" occurs is: 2
def check_Search_WordCount(mySearchStr, mySentence):
len_mySentence = len(mySentence)
len_Sentence_without_Find_Word = len(mySentence.replace(mySearchStr,""))
len_Remaining_Sentence = len_mySentence - len_Sentence_without_Find_Word
count = len_Remaining_Sentence/len(mySearchStr)
return (int(count))
I assume that you just know about python string and for loop.
def count_occurences(s,word):
count = 0
for i in range(len(s)):
if s[i:i+len(word)] == word:
count += 1
return count
mystring = "This sentence is a simple sentence."
myword = "sentence"
print(count_occurences(mystring,myword))
explanation:
s[i:i+len(word)]: slicing the string s to extract a word having the same length with the word (argument)
count += 1 : increase the counter whenever matched.

Categories