Skip to content
← Back to Community
I need help with a python program.
Profile icon
randyjgarcia

So basically in python if the string contains the sub string and it occurs more than once I am supposed to return "yes", and if it doesn't occur more than once then i'm supposed to return "no". I need help on how to find the sub string within a string and whether or not it occurs more than once. I am not sure if I am supposed to use a if statement or not.

Voters
Profile icon
totallynotangelica1
Profile icon
randyjgarcia
Comments
hotnewtop
Profile icon
Geocube101

Use the built in method count, it returns the number of substring occurrences in a string
Syntax: string.count(substring[, start, end])
Params:

  • string - The string to search
  • substring - The substring to search for
  • start - Index of where to begin search (Optional)
  • end - Index of where to end search (Optional)

Then you can test if the count is greater than 1

substr_count = string.count(subtring) if substr_count > 1: print('Yes') else: print('No')
Profile icon
randyjgarcia

@Geocube101 If you would scroll down, It outputs all No's when I tried to incorporate your suggestion into the code.

substring = "aplus"

String = []
String.append("dog#cat#pigaplus")
String.append("pigs#apluscompsci#food")
String.append("##catgiraffeapluscompsci")
String.append("apluscatsanddogsaplus###")
String.append("###")
String.append("aplusdog#13337#pigaplusprogram")
String.append("code#H00P#code1234")
String.append("##wowgira77##eplus")
String.append("catsandaplusdogsaplus###")
String.append("7")

Iterations = len(String)
substr_count = String.count(substring)
for x in range(0, Iterations):
if substr_count > 1:
print('Yes')
else:
print('No')

Profile icon
Geocube101

@randyjgarcia You're using this method on a list, in which count will only test if an entire element equals the substring.
For using this in a list while testing if a list's string elements contain a subtring try...

occurrences = [] #"String" is your list of strings for string in String: occurrences.append(string.count(substring))

This will store how many times each string in your list has a substring occurrence
The length of occurrences in this code should equal the length of your array

Profile icon
randyjgarcia

@Geocube101 I understand everything you are saying, but when I do everything it compiles with no errors but doesn't output anything.

Profile icon
Geocube101

@randyjgarcia Can you link the repl?

Profile icon
randyjgarcia
Profile icon
randyjgarcia
Profile icon
Geocube101

@randyjgarcia I think I got it

Profile icon
randyjgarcia

@Geocube101 OHHH okay I didn't know where to put the for string in String, thanks a lot you were a ton of help! its a cool little program right? lol

Profile icon
Geocube101

You're welcome @randyjgarcia