Using a list of strings in an if statement [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have several lists that are structured as follows
list_01= [['Little Line', '15']]
list_02= [['Long Line', '20']]
Later on in the code after these lists I want to create a function that defines the creation of lines that I want to work as follows. If the items in the list equal the strings 'Little Line' and '15', it will create a little line.
def draw_line(dataset):
if dataset[0[0]]==('Little Line'):
left(dataset[0[1]])
foward(25)
Later, I can then call this function as follows later on in the code:
draw_line(list_01)
to create the line. The code I've described is pretty similar to my current code and shows how I believe it should work. I understand this should probably be pretty basic code, but I'm experiencing errors and can't quite figure out how it should work.

Your syntax for accessing nested lists is wrong. Instead of
dataset[0[0]]
you need to do
dataset[0][0]
But in general, a list is not a reasonable datatype for this. A dictionary would make a lot more sense:
moves = {
"Little line": 15,
"Long line": 20,
# etc.
}
and then do something like
def draw_line(dataset):
left(dataset[0])
forward(25)

Related

How do I check if a string contains ANY element in an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to detect if a string contains any element in an array. I want to know if the string(msg) has any element from the array(prefixes) in it.
I want this because I want to make a discord bot with multiple prefixes, heres my garbage if statement.
if msg.startswith(prefixes[any]):
The existing answers show two ways of doing a linear search, and this is probably your best choice.
If you need something more scalable (ie, you have a lot of potential prefixes, they're very long, and/or you need to scan very frequently) then you could write a prefix tree. That's the canonical search structure for this problem, but it's obviously a lot more work and you still need to profile to see if it's really worthwhile for your data.
Try something like this:
prefixes = ('a','b','i')
if msg.startswith(prefixes):
The prefixes must be tuple because startswith function does not supports lists as a parameter.
There are algorithms for such a search, however, a functional implementation in Python may look like this:
prefixes = ['foo', 'bar']
string = 'foobar'
result = any(map(lambda x: string.startswith(x), prefixes))
If you search for x at any position in string, then change string.startswith(x) to x in string.
UPDATE
According to #MisterMiyagi in comments, the following is a more readable (possibly more efficient) statement:
result = any(string.startswith(prefix) for prefix in prefixes)

Can I compare a string with a list in Python 3? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a large string of text which I wish to search for certain words. The words are stored in a list. Is it possible (and if so then how) to compare the string with the words in the list so that python returns all the found words and their locations, like this;
text = 'Theres a voice that keeps on calling me. Down the road, thats where Ill always be. Every stop I make, I make a new friend. Cant stay for long, just turn around and Im gone again. Maybe tomorrow, Ill want to settle down, Until tomorrow, I’ll just keep moving on.'
search_list = ['voice', 'Until', 'gone']
print(compare(text, search_list))
#returns something like: {voice: 11, Until: 112, gone: 54}
#p.s. the locations are random since I couldn't be bothered to count the characters
#but the format is something like {found_term: position of first character}
#(compare doesn't necessarily have to return the results in dictionary format)
I have tried searching on stack overflow and google but most similar questions are about comparing 2 strings or 2 lists.
Thank you in advance.
You can use .index() on a string to get the position of a substring:
from typing import List, Dict
def compare(text: str, search_list: List[str]) -> Dict[str, int]:
return {
word: text.index(word)
for word in search_list
}

Python variable does not contain any data [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm hoping this is a simple stupid problem. But we have an in-house program that is no longer working. The program is not able to pass the data which is supposed to be contained in a variable using var_name+="".
The variable seemingly contains nothing. when I try to print the contents of this variable to either a string or text doc, we get nothing. The variable in question here is "allData".
The contents of this variable need to be passed to our fax appliance.
def sendFax(destOrg, destFax, cliName, casenum, attachments, errEAddr, comment, destName):
creds=requests.auth.HTTPBasicAuth(user,password)
#OVERRIDE OUTBOUND FAX NUMBER FOR TESTING
destFax='716-631-9804'
print("faxes will be sent to "+destFax)
return
allData=''
allData+='<schedule_fax>\n'
allData+='<cover_page>\n'
allData+='<url>'+prepXMLString(coverPage)+'</url>\n'
allData+='<enabled>true</enabled>\n'
allData+='<subject>'+prepXMLString(cliName)+' - case # '+str(casenum)+'</subject>\n'
allData+='<comments>'+prepXMLString(comment)+'</comments>\n'
allData+='</cover_page>\n'
allData+='<sender>\n'
allData+='<name>'+prepXMLString(webAddr)+'</name>\n'
allData+='<organization>'+prepXMLString(ourOrg)+'</organization>\n'
allData+='<phone_number>'+prepXMLString(ourPhonenum)+'</phone_number>\n'
allData+='<fax_number>'+prepXMLString(ourFaxnum)+'</fax_number>\n'
allData+='<email_address>'+prepXMLString(errEAddr)+'</email_address>\n'
allData+='</sender>\n'
allData+='<recipient>\n'
allData+='<name>'+prepXMLString(destName)+'</name>\n'
allData+='<organization>'+prepXMLString(destOrg)+'</organization>\n'
allData+='<fax_number>'+destFax+'</fax_number>\n'
allData+='</recipient>\n'
That is all screwed up. You're returning on the line with the return keyword which is why nothing is being returned.
You should do all of the concatenation and then return.

Explanation of str.partition() in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having a hard time understanding str.partition() function in python. I have read the definition of the function and searched online without finding an explanation that makes sense to me.
I have some code that uses it pretty heavily and have been trying to understand it. I could post the code if it would help but it is a pretty precise code segment that would probably complicate things.
Need in-depth, probably low-level, explanation of str.partition() function in python.
The docs are pretty clear ...
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
So ...
>>> 'test'.partition('s')
('te', 's', 't')
>>> 'test'.partition('a')
('test', '', '')
You either get the front, splitter character, and tail, or you get the full string and two blank strings (depending on whether or not the partition character is present).

Assuming that s is a string of lower case characters. how would i find the number of string y inside s [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
the following problem in python please .....
Assuming that s is a string of lower case characters.
how would I write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then my program would print
'Number of times bob occurs is: 2'
I am a completely new to python and appreciate any help
If you didn't want to count overlapping bobs as separate values, this would be easy:
s.count('bob')
But you apparently do. (I had to guess that, based on the fact that your intended output is 2 rather than 1… in the future, it would be better to explain your problem instead of leaving it ambiguous.) As the help says, count returns "the number of non-overlapping occurrences of substring sub…", so that won't do any good.
So, for that, you will have to do it manually. I'll show an example that should have enough to get you started:
for i in range(len(s)):
if s[i:].startswith('bob'):
print('Found a bob')
A slightly smarter way to do this would be to use the find method on strings. You can find details on this in the online docs, or by typing help(str.find) in the interactive console. Notice that find takes a start argument. You should be able to figure out how this would help you; it may take a bit of work to get the details right, but if you get stuck, you can always post a new question asking for specific help.
You can try this way
string = "BOBOBOBOBOABCDE"
search = "BOB"
print len([i for i in range(len(string)) if string.startswith(search, i)])

Categories