Values find a word

Hello so I have to do a program that identifies all of the positions where a word occurs in a list but when I run my program it doesn’t output anything.
Here’s my code :

sentence =("ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY") #This is a list
print (sentence)
text = input("Choose a word from the sentence above")#this prints out some text with an input 
sentence = sentence.split(" ")# This splits the list 
text = text.upper ()# this makes the text in capital letters
def lookfor ():
    if text in sentence:
        for i in sentence:
            value = sentence.index(sentence)
            print ("Your word has been found in the sentence at the position", value + "and", value )


        else:
            print ("The word that you have typed is not found in the sentence.")

Thank you

asked May 25, 2016 at 12:38

tom3883's user avatar

3

To answer your questions, nothing is happening because you aren’t calling the function.

There’s a lot of work remaining on your function, but here are some general tips:

1) Index only finds the first instance of an element in a list

2) You can’t be sure that a word is in your sentence exactly twice

3) Use descriptive variable names. For example, for word in sentence makes a lot more sense intuitively

answered May 25, 2016 at 12:51

Jeremy Weirich's user avatar

You can do something like this:

sentence =("ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY") #This is a list
print (sentence)
text = raw_input("Choose a word from the sentence above: ")#this prints out some text with an input 
sentence = sentence.split(" ")# This splits the list 

text = text.upper ()# this makes the text in capital letters
def lookfor (text):
    indexes = [ idx+1 for word, idx in zip(sentence, range(0,len(sentence))) if text == word ]
    print ("Your word has been found in the sentence at these positions", indexes )

    if not indexes:
         print ("The word that you have typed is not found in the sentence.")

lookfor(text)

Example:

ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY
Choose a word from the sentence above: for
('Your word has been found in the sentence at these positions', [8, 14])

answered May 25, 2016 at 12:54

YOBA's user avatar

YOBAYOBA

2,73914 silver badges28 bronze badges

3

10000+ результатов для ‘find a word’

Fruit find a word

Fruit find a word
Найди пару

от Englikatpt

Find a different word

Find a different word
Найди пару

от Mrsog

Rainbow 2

Rainbow 2
Поиск слов

от Iradamika80

search a word

Rainbow2

Rainbow2
Поиск слов

от Iradamika80

search a word

find a word

find a word
Поиск слов

от Polinabrilts

Find a word!

Find a word!
Поиск слов

от Es4

Find a word

Find a word
Поиск слов

от Dextersnow6

Find a word

Find a word
Поиск слов

от Natanatanata

Find a word

Find a word
Поиск слов

от Margarita113

Find a word

Find a word
Поиск слов

от Irenen

Find a word

Find a word
Найди пару

от Olgabrui

Spotlight 4

Find a word

Find a word
Поиск слов

от Elenapshenitsyna

find a word

find a word
Поиск слов

от Lena840684

Find a word! Unit 10

Find a word! Unit 10
Поиск слов

от Morevaks

Find a word! Unit 7

Find a word! Unit 7
Поиск слов

от Morevaks

Find a word! Unit 9

Find a word! Unit 9
Поиск слов

от Morevaks

Find a pair (a word + a picture)

Find a pair (a word + a picture)
Совпадающие пары

от 1buryaninaalexa

9-й класс
English

Find a right word. Grammar basic

Find a right word. Grammar basic
Пропущенное слово

от Xsyrova

Find a word for a definition

Find a word for a definition
Найди пару

от Uliasolo851

Find a word - Days of the week

Find a word — Days of the week
Поиск слов

от Annglukhova

Find a synonym for each word

Find a synonym for each word
Найди пару

от Gallyamova21

Высшее образование

 Past Simple Irregular Find-A-Word

Past Simple Irregular Find-A-Word
Поиск слов

от Michaelbk

Find the definition of a word 1

Find the definition of a word 1
Сопоставить

от Ashkrykina

Find a word: Over the garden wall

Find a word: Over the garden wall
Поиск слов

от Tsama1897

Find a correct word (-ment / -ness)

Find a correct word (-ment / -ness)
Групповая сортировка

от Chenmenli

International Women's Day (Find a word)

International Women’s Day (Find a word)
Поиск слов

от Csc

FIND WORD

FIND WORD
Групповая сортировка

от Dmitriyperm

9-й класс

OGE/EGE Word formation

OGE/EGE Word formation
Пропущенное слово

от Ma1204

9-й класс
10-й класс
11 класс
Средняя школа
Word formation

Find a missing word.

Find a missing word.
Пропущенное слово

от Zshelemba

10-й класс
11 класс
English

find the appropriate word

find the appropriate word
Пропущенное слово

от Nicolemilaeva

Find the right word

Find the right word
Пропущенное слово

от Shrvski

Средняя школа
English

The Parent trap 30-40 find a word

The Parent trap 30-40 find a word
Пропущенное слово

от Maiborodaed

films

find the word

find the word
Пропущенное слово

от 2happynatalie

Find the right word

Find the right word
Пропущенное слово

от Pegajane

5-й класс
Средняя школа
English
Afanasyeva Workbook

Find the word/ Spotlight 2/ Letters A-H

Find the word/ Spotlight 2/ Letters A-H
Анаграмма

от Nel777

Find a word As3 p 6-7 lesson 1

Find a word As3 p 6-7 lesson 1
Откройте поле

от Nastyaovchinnik1

Find the word 2

Find the word 2
Найди пару

от Lovelypost

Find the word 1

Find the word 1
Найди пару

от Lovelypost

Packing - find a pair

Packing — find a pair
Совпадающие пары

от Olgabalitskaya

food
Spotlight 4

Find mistakes

Find mistakes
Случайные карты

от Arisha2103

kids
English
many/much/a lot of/ a few/ a little

Drinks - find a pair

Drinks — find a pair
Совпадающие пары

от Katerinastashev

discover english starter

FF_2 find the word

FF_2 find the word
Поиск слов

от World2112

Find the missing word

Find the missing word
Пропущенное слово

от Melenatel30

Things find the word

Things find the word
Поиск слов

от Heini92

Module 2. Find the word.

Module 2. Find the word.
Найди пару

от Aleks4ndrakoste

Spotlight 4

find the word!

find the word!
Поиск слов

от Dasalublina

Find the word

Find the word
Сопоставить

от Amint

Find the word

Find the word
Случайные карты

от Annaschipanova2

Find the word

Find the word
Сопоставить

от Umrashed1981s

Find the word

Find the word
Поиск слов

от Mkurkova1

Find an extra word

Find an extra word
Викторина

от Elvina34

emotions: find the word

emotions: find the word
Поиск слов

от Lakhmanovas

Find the word

Find the word
Погоня в лабиринте

от Natef005

Find the word

Find the word
Привести в порядок

от Hop

Find the different word

Find the different word
Диаграмма с метками

от Lana2300

Find the word

Find the word
Поиск слов

от Bokuwaerudes

8 класс
English
Spotlight 8

Find the Word (Sport)

Find the Word (Sport)
Поиск слов

от Proteacheronline

Find the word

Find the word
Поиск слов

от Reallity2013

Find the word

Find the word
Поиск слов

от Anastasia1994s

Find the odd word

Find the odd word
Викторина

от Katesa

In this post, we are finding a word or substring in the String. The String is a sequence of characters and a class in Java.

To find a word in the string, we are using indexOf() and contains() methods of String class.

The indexOf() method is used to find an index of the specified substring in the present string. It returns a positive integer as an index if substring found else returns -1.

The contains() method is used to check whether a string contains the specified string or not. It returns a boolean value either true or false. If the specified string is found then it returns true, false otherwise.

Time for an Example:

Let’s create an example to find a word in the string. Here, we are using indexOf() method that returns an index of the specified substring. See the example below.

public class Main {
	public static void main(String[] args){
		String str = "This sentance contains find me string";
		System.out.println(str);
		// find word in String
		String find = "find me";
		int i = str.indexOf(find);
		if(i>0)
			System.out.println(str.substring(i, i+find.length()));
		else 
			System.out.println("string not found");
	}
}

This sentance contains find me string
find me

Example 2

Let’s create another example to find a word in the string. Here, we are using the contains() method that returns true, if the specified string is found. See the example below.

public class Main {
	public static void main(String[] args){
		String str = "This sentance contains find me string";
		System.out.println(str);
		// find word in String
		String find = "find me";
		boolean val = str.contains(find);
		if(val)
			System.out.println("String found: "+find);
		else 
			System.out.println("string not found");
	}
}

This sentance contains find me string
String found: find me



To find a word in a file using Python:

  1. Specify a target word.
  2. Open a file.
  3. Loop through the file line by line.
  4. Check if any line has the target word. If it does, print the line number and end the loop.

For example, let’s check where (if any) the word “test” is in a file called “example.txt”.

word = "test"

with open("example.txt", "r") as file:
    for line_number, line in enumerate(file, start=1):  
        if word in line:
          print(f"Word '{word}' found on line {line_number}")
          break

print("Search completed.")

In my case, the word is found in the second line. So the output is:

Word 'test' found on line 2
Search completed.

(The enumerate(file, start=1) matches each line with an index. Line 1 has an index of 1, line 2 has an index of 2, and so on. This simplifies the loop. Check out this article to learn more about enumerating in Python.)

How to Find the Longest Word in a File Using Python

To find the longest word(s) in a file:

  1. Open a file.
  2. Store the words in memory.
  3. Find the longest word.
  4. Find other possible words that are equally long.

For example, let’s find out the longest words in a file called “example.txt”:

with open("example.txt", "r") as file:
    words = file.read().split()

longest_word = max(words, key=len)
longest_words = [word for word in words if len(word) == len(longest_word)]

print(longest_words)

If you are confused, the max() function:

  • Loops through the words
  • Applies len function on each word.
  • Returns the word with the greatest value returned by the len. In other words, the longest word.

Also, learn more about list comprehensions to create shorthand for loops like the one in the last line.

How to Find and Replace a Word in a File Using Python

To find and replace a word in a file with Python:

  1. Open a file.
  2. Read the file in memory.
  3. Find and replace specific words.
  4. Write the fixed-up data back to the file.

Here is an example:

# Read the file in memory
with open("example.txt", "r") as file:
  data = file.read()

# Replace matches
data = data.replace("test", "banana")

# Write the data back to the file
with open("example.txt", "w") as file:
  file.write(data)

Thanks for reading. Happy coding!

Further Reading

  • How to Find All Files With Extension
  • How to Write to a File in Python
  • The with Statement in Python

About the Author

I’m an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.

Recent Posts

Solved/Closed

Hello,

I’d like to scan a column for a certain word (e.g. «apple») and put a code (e.g. «A») on the cell next to it each time it finds it. In this case, «apple» might be by itself or in the middle of a sentence.

System Configuration: Windows XP Internet Explorer 7.0

Related:

  • Vlookup if cell contains a word within text

  • Excel if cell contains word then assign value
    — Best answers

  • Excel formula find text in cell
    — Best answers

  • If cell contains (multiple text criteria) then return (corresponding text criteria)


    Excel Forum

  • Excel conditional formatting if another cell contains specific text


    Excel Forum

  • Highlight cell if another cell contains text


    Excel Forum

  • Count if cell contains number

    Excel Forum

  • Word free for u

    Guide

10 replies


mubashir aziz


Posts

190

Registration date
Sunday April 12, 2009
Status
Member
Last seen
February 16, 2010

160

Updated on Dec 21, 2018 at 04:21 AM

Hi,

Suppose your data is from A1 to A100 or onward. Then in B1, copy this formula and drag it down:

=IF(ISERROR(SEARCH("*apple*",A1,1)),"","A ")

Hope, it will help!

Never ashamed to get or give Advise.

Muhammad Mubashir Aziz , Lodhran, Pakistan

Similar discussions

Like this post? Please share to your friends:
  • Valueerror excel file format cannot be determined you must specify an engine manually
  • Value что это значит excel
  • Value по русски функция excel
  • Value в ячейке excel
  • Value в excel что означает