Looking through a string but avoiding substring - string

I need to check if a string appear in a text. I want to avoid substring.
string = "one"
text = "bees make honey
if string in text
This return True of course. How do i avoid this issue?

Well, "one" does appear in "bees make honey", as a substring.
But if you want to see if "one" is a word or not, you can use the split() function.
By words, I mean bees, make, and honey.
Sample python implementation:
l = parentString.split(' ') # Returns ['bees','make','honey']
if childString in l:
print('Word found in parent text')
else:
print('Word not found in parent text')

Related

How to return the result of print statement in a function call in python?

I am a beginner and I am having a problem returning a value in python.
The Question is as follows:
Write a function called get_capitals. get_capitals should
accept one parameter, a string. It should return a string
containing only the capital letters from the original
string: no lower-case letters, numbers, punctuation marks,
or spaces.
In short, the function should return the string which will only contain capital letters.
My code is:
def get_capitals(a_string):
for x in a_string:
ordinal_number=ord(x)
if ordinal_number>=60 and ordinal_number<=90:
print(x,end=""))
# print(ordinal_number)
Using function call
print(get_capitals("CS1301"))
call with the above call the above code i am able to print the result i desire but it returns None.
which I am trying to avoid.
Can someone tell me how can I return a result of the print function?
Use list comprehension and join
def get_capitals(a_string):
return ''.join(c for c in a_string if c.isupper())
As far as my understanding goes, You need a program that only returns letters that is in Capital in a String. I developed a program, have a look.
My Code:
def get_capitals (a_string):
upper_case_chars = ""
for i in a_string:
if i.isupper():
upper_case_chars = upper_case_chars + i
return upper_case_chars
print (get_capitals("CSFF57456"))

Will it help in this problem to convert the string into a list?

I have a question. I am not looking for the answer to this exercise, just a pointer. My question is: will this be easier to solve if the two-word string is converted to a List?
ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter
animal_crackers('Levelheaded Llama') --> True
animal_crackers('Crazy Kangaroo') --> False
Yes, in this problem it would help to use the .split() method to split the string into a list of the two words.
Generally, the same data can be represented in different ways, and you want to use a representation which aligns with what you need to do with the data. Since this problem is about words, then "a list of words" aligns closer with what you need to do than "a string with two words" does.
Having a list of words allows you to write code that refers to "the first word" (i.e. words[0]) and "the second word" (i.e. words[1]). There is no comparably-simple way to refer to individual words in the original string.
Thanks everyone. I realised quite soon after i posted that the .split() function was what i needed to use. This was my solution.
def animal_crackers(string):
twoWords = (string.split(' '))
if twoWords[0][0].upper() == twoWords[1][0].upper():
return True
Do a split on the string input myListOfTwoSriting = stringInput.split(" "), next split the 2 string link that : firstletter = myListOfTwoSriting [0].split("")[0] then firstletterOfSeconde = myListOfTwoSriting [1].split("")[0] for the seconde.
next:
if firstletter == firstletterOfSeconde :
return True
else:
return False

Overlapping values of strings in Python

I am building a puzzle word game in Python. I have the correct puzzle word, and the guessed puzzle word. I want to build a third string which shows the correct letters in the guessed puzzle in the correct puzzle word, and _ at the position of the incorrect letters.
For example, say the correct word is APPLE and the guessed word is APTLE
then i want to have a third string: AP_L_
The guessed word and correct word are guaranteed to be 3 to 5 characters long, but the guessed word is not guaranteed to be the same length as the correct word
For example, correct word is TEA and the guessed word is TEAKO, then the third string should be TEA__ because the players guessed the last two letters incorrectly.
Another example, correct word is APPLE and guessed word is POP, the third string should be:
_ _ P_ _ (without space separation)
I can successfully get the matched indexes of the correct and guessed word; however, I am having problems building the third string. I just learned that strings in Python are immutable and that i cannot assign something like str1[index] = str2[index]
I have tried many things, including using lists, but i am not getting the correct answer. The attached code is my most recent attempt, would you please help me solve this?
Thank you
find the match between puzzle_word and guess
def matcher(str_a, str_b):
#find indexes where letters overlap
matched_indexes = [i for i, (a, b) in enumerate(zip(str_a, str_b)) if a == b]
result = []
for i in str_a:
result.append('_')
for value in matched_indexes:
result[value].replace('_', str_a[value])
print(result)
matcher("apple", "allke")
the output result right now is list of five "_"
cases:
correct word is APPLE and the guessed word is APTLE third
string: AP_L_
correct word is TEA and the guessed word is TEAKO,
third string should be TEA__
correct word is APPLE and guessed
word is POP, third string should be _ _ P_ _
You can use itertools.zip_longest here to always make sure you pad out to the longest word provided and then create a new string by joining the matching characters or otherwise a _. eg:
from itertools import zip_longest
correct_and_guess = [
('APPLE', 'APTLE'),
('TEA', 'TEAKO'),
('APPLE', 'POP')
]
for correct, guess in correct_and_guess:
# If characters in same positions match - show character otherwise `_`
new_word = ''.join(c if c == g else '_' for c, g in zip_longest(correct, guess, fillvalue='_'))
print(correct, guess, new_word)
Will print the following:
APPLE APTLE AP_LE
TEA TEAKO TEA__
APPLE POP __P__
Couple of things here.
str.replace() does not replace inline; as you noted strings are immutable, so you have to assign the result of replace:
result[value] = result[value].replace('_', str_a[value])
However, there's no point doing this since you can just assign to the list element:
result[value] = str_a[value]
And finally you can assign a list of the length of str_a without the for loop, which might be more readable:
result = ['_'] * len(str_a)

How can I replace each letter in the sentence to sentence without breaking it?

Here's my problem.
sentence = "This car is awsome."
and what I want do do is
sentence.replace("a","<emoji:a>")
sentence.replace("b","<emoji:b>")
sentence.replace("c","<emoji:c>")
and so on...
But of course if I do it in that way the letters in "<emoji:>" will also be replaced as I go along. So how can I do it in other way?
As Carlos Gonzalez suggested:
create a mapping dict and apply it to each character in sequence:
sentence = "This car is awsome."
# mapping
up = {"a":"<emoji:a>",
"b":"<emoji:b>",
"c":"<emoji:c>",}
# apply mapping to create a new text (use up[k] if present else default to k)
text = ''.join( (up.get(k,k) for k in sentence) )
print(text)
Output:
This <emoji:c><emoji:a>r is <emoji:a>wsome.
The advantage of the generator expression inside the ''.join( ... generator ...) is that it takes each single character of sentence and either keeps it or replaces it. It only ever touches each char once, so there is no danger of multiple substitutions and it takes only one pass of sentence to convert the whole thing.
Doku: dict.get(key,default) and Why dict.get(key) instead of dict[key]?
If you used
sentence = sentence.replace("a","o")
sentence = sentence.replace("o","k")
you would first make o from a and then make k from any o (or a before) - and you would have to touch each character twice to make it happen.
Using
up = { "a":"o", "o":"k" }
text = ''.join( (up.get(k,k) for k in sentence) )
avoids this.
If you want to replace more then 1 character at a time, it would be easier to do this with regex. Inspired by Passing a function to re.sub in Python
import re
sentence = "This car is awsome."
up = {"is":"Yippi",
"ws":"WhatNot",}
# modified it to create the groups using the dicts key
text2 = re.sub( "("+'|'.join(up)+")", lambda x: up[x.group()], sentence)
print(text2)
Output:
ThYippi car Yippi aWhatNotome.
Doku: re.sub(pattern, repl, string, count=0, flags=0)
You would have to take extra care with your keys, if you wanted to use "regex" specific characters that have another meaning if used as regex-pattern - f.e. .+*?()[]^$

Remove part of string (regular expressions)

I am a beginner in programming. I have a string for example "test:1" and "test:2". And I want to remove ":1" and ":2" (including :). How can I do it using regular expression?
Hi andrew it's pretty easy. Think of a string as if it is an array of chars (letters) cause it actually IS. If the part of the string you want to delete is allways at the end of the string and allways the same length it goes like this:
var exampleString = 'test:1';
exampleString.length -= 2;
Thats it you just deleted the last two values(letters) of the string(charArray)
If you cant be shure it's allways at the end or the amount of chars to delete you'd to use the version of szymon
There are at least a few ways to do it with Groovy. If you want to stick to regular expression, you can apply expression ^([^:]+) (which means all characters from the beginning of the string until reaching :) to a StringGroovyMethods.find(regexp) method, e.g.
def str = "test:1".find(/^([^:]+)/)
assert str == 'test'
Alternatively you can use good old String.split(String delimiter) method:
def str = "test:1".split(':')[0]
assert str == 'test'

Resources