See if string contains substring - python

I was looking for a way to write code that checks whether a certain string is a part of another string. I understand that it is easy to do when we have numbers, but I don't know how to do it with strings.
For example, I have this function
a = is_part("motherland", "land")
I need to know that "land" is a part of the word "motherland" (return True or False). Is it possible to check this?
UPDATE: How can I create a restriction when the second word always has to be in the end of the first one. For example, in case when I check whether "eight" is a part of "eighteen" it returns False because "eight" is not at the end of the first word

This should help:
>>> "land" in "motherland"
True
>>> "banana" in "motherland"
False

Here is a function that determines whether a string target is contained within another string some_string.
def is_part(some_string, target):
return target in some_string
>>> is_part('motherland', 'land')
True
>>> is_part('motherland', 'father')
False
>>> is_part('motherland', '')
True
If you don't like an empty string returning true, change the return statement to
return (target in some_string) if target else False
If, on the other hand, you need to implement it yourself:
def is_part(some_string, target):
if target:
target_len = len(target)
for i in range(len(some_string)):
if some_string[i:i+target_len] == target:
return True
return False

Related

How to make letters in a string match

I wasn't sure what to title it, but I'm writing a function that checks if a phrase is a palindrome or not. If something is capitalized or not doesn't matter and if there are other characters it will remove them. If the string is the same forwards and backwards (that's what a palindrome is) then it will be a Boolean True, and a Boolean False if it isn't. For example:
is_palindrome('ta.cocat')
#It would return
True
is_palidrome('Tacocat')
#It would return
True
is_palindrome('tacodog')
#It would return
False
I've written code that will take out extra characters, but I can't figure out how to make it that capitalization doesn't matter.
#Strip non-alpha
def to_alphanum(str):
return ''.join([char for char in str if char.isalnum()])
#Palindromes
def is_palindrome(str):
str = to_alphanum(str)
if(str==str[::-1]):
return True
else:
return False
#Here's examples about what it returns
is_palindrome('taco.cat')
True
is_palindrome('Tacocat')
>>> False
just use the lower function on your input string, so that case doesnt matters in your function
str = to_alphanum(str).lower()
You can simply use:
def isPalindrome(s):
s = to_alphanum(s).lower()
rev = s[::-1]
# Checking if both string are equal or not
if (s == rev):
return True
return False
s1 = "malayalam"
>>> isPalindrome(s1)
True

How to make string characters lower case and uppercase match in python

I wasn't sure what to title it, but I'm writing a function that checks if a phrase is a palindrome or not. If something is capitalized or not doesn't matter and if there are other characters it will remove them.
If the string is the same forwards and backwards (that's what a palindrome is) then it will be a Boolean True, and a Boolean False if it isn't.
For example:
is_palindrome('ta.cocat')
#It would return
True
is_palidrome('Tacocat')
#It would return
True
is_palindrome('tacodog')
#It would return
False
I've written code that will take out extra characters, but I can't figure out how to make it that capitalization doesn't matter.
#Strip non-alpha
def to_alphanum(str):
return ''.join([char for char in str if char.isalnum()])
#Palindromes
def is_palindrome(str):
str = to_alphanum(str)
if(str==str[::-1]):
return True
else:
return False
#Here's examples about what it returns
is_palindrome('taco.cat')
True
is_palindrome('Tacocat')
>>> False
just use the lower function on your input string, so that case doesnt matters in your function
str = to_alphanum(str).lower()

Function that returns true or false if certain conditions are met?

So a user will input a string value in binary format. i.e. '01000001'
I want to check the value they enter to see if it:
has only eight characters.
is a string type
and only contains '0's or '1's
preferably to be done with a function that takes in the user value so that i can call it whenever. Returns false if conditions are not met.
this is what i came up with so far...
size = len(teststring)
teststring = '11111111'
def typecheck(value):
if type(user_input) == type(teststring) and len(user_input) == size and contains only 1 | 0
return
You can use regex matching here:
reg = re.compile(r'^[01]{8}$')
def typecheck(value):
return isinstance(value, str) and bool(reg.match(value))
Or since you want to check for binary format number, how about converting it to int with base 2, and see if it's a valid conversion:
def typecheck(value):
try:
return len(value) == 8 and bool(int(value, 2))
except TypeError, ValueError:
return False
No need for regex
You could use str.strip() and strip all 1 and 0 from end and beginning and check.
Code:
check = "11101110"
if isinstance(check,str) and len(check)==8 and check.strip("01")=='':
print "yes"
Output:
yes
This can be done with one if statement. If the regex doesn't find a match it will return None which evaluates to False in a truth test.
import re
def check_input(user_input):
if not re.match(r'^[01]{8}$', user_input):
it doesn't meet requirements do something

In Python, how do I check if a string has only alphabets without the built in functions(.islower etc)?

This is my code. it seems to be checking only the first character. I'd like to know how to fix it.
import string
ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DECIMAL_DIGITS = "0123456789"
ALPHABETS = ASCII_LOWERCASE + ASCII_UPPERCASE
def is_alpha(string):
for c in "string":
if c in ALPHABETS:
return False
else:
return True
Do not return in every iteration, only return False when you find something that is not in ALPHABET. What about this?
def is_alpha(your_string):
for c in your_string:
if c not in ALPHABETS:
return False
return True
actually its almost half right:
def is_alpha(string):
for c in string:
if not c in ALPHABETS:
return False
return True
short circuiting on False is ok but you need to finish the loop to determine True
There's several issues with your code here.
In your function definition you say
for c in "string"
which means you're checking the characters in the string literal "string".
You'll need to remove the quotes to have it refer to your parameter and actually check the string you're looking at. Further, you should change the name of your parameter and variable to something less ambiguous than string.
As Two-Bit Alchemist points out, you're returning from inside the loop so if the first character is in ALPHABETS then it returns and doesn't execute any more.
Which goes to the final issue. You're returning False if it is an alpha character instead of true. If you change
if c in ALPHABETS:
return False
to
if c not in ALPHABETS:
return False
then delete the else branch and put the return True after the loop it will work as you intend.
Change your function like this:
def is_alpha(string):
for c in string:
if c not in ALPHABETS:
return False
return True
First of all, you had for c in "string": in your code. There you are creating a new string ("string") and looping through the characters in it. Instead, you want to loop through the parameter passed to your function. So remove the double quotes.
Your function returns after first character because you are returning in both cases. Return true only when all characters are in ALPHABETS

Unsure of for loop

Not sure what I'm doing wrong here. Any help would be appreciated. When I enter a DNA sequence that contains a bad variable (like Z) I keep getting a return True. Can someone point out why?
Thanks
def is_valid_sequence(dna):
""" (str) -> bool
>>> is_valid_sequence('ATCG')
True
>>> is_valid_sequence('AZT')
False
>>> is_valid_sequence('atcg')
False
Returns a boolean result based on whether dna is a valid
dna sequence.
"""
for char in dna:
if char in "TCGA":
return True
else:
return False
You're returning on the first iteration of the loop: return ends the function, and all paths in the body of your loop contain a return. You probably want
for char in dna:
if char not in 'TCGA':
return False
return True
Or, more Pythonically:
return all(char in 'TCGA' for char in dna)
In your code you take char one by one and return True if it is in "TCGA". So if the first char is in "TCGA" it would return True and will stop execution. You should do something like this:
for char in dna:
if char not in "TCGA":
return False
You're always returning after testing the first character. Keep testing until you reach a bad character, don't return True until you've tested the whole string.

Categories

Resources