Explanation of str.partition() in python [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 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).

Related

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
}

Regex for getting everything in between brackets, including parentheses [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 string I am trying to create a regex for in order to extract everything inside the brackets. An example of such a string is as follows
[-At(A),+CarAt(B),-CarAt(A),-InCar]
The current regex I'm using is re.search(r'\[.*?\]', string), but this only returns -At(A),-InCar instead of -At(A),+CarAt(B),-CarAt(A),-InCar
I am not sure why it's matching one set of parentheses in -At(A); I thought the regex I had would work because it would match everything between the brackets.
How can I get everything inside the brackets of my original string?
I think the problem is with the question mark. Because question marks, when they come after a quantifiers make them 'lazy'.
So try to use:
r'\[.*\]'
You didn't say you wanted the contained members, but I suspect it to be the eventual case
To do so, I've found it better to slice or .strip() brackets off and then .split() this sort of string to get its members before doing further validation
>>> s = "[-At(A),+CarAt(B),-CarAt(A),-InCar]"
>>> s = s.strip('[]')
>>> s
'-At(A),+CarAt(B),-CarAt(A),-InCar'
>>> values = s.split(',')
>>> values
['-At(A)', '+CarAt(B)', '-CarAt(A)', '-InCar']
Using a regex to validate the individual results of this is often
easier to write and explain
is better at highlighting mismatches than re.findall(), which will silently omit mismatches
can be much more computationally efficient (though it may not be for your case) than trying to do the operation in a single step (ex1 ex2)
>>> import re
>>> RE_wanted = re.compile(r"[+-](At|Car|In){1,2}(\([A-Z]\))?")
>>> all((RE_wanted.match(a) for a in values))
True

Python returns null when using regex [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 am trying to use regex to see if the given string is an IPv4 address. I want to return a boolean value True/False depending on the string. This is my code:
import re
def isIPv4Address(inputString):
pattern = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s')
return pattern.match(inputString)
The value is null. At this point, I can tell that the function does not return a boolean value. However, all questions I see about regex and IP addresses is about writing the pattern instead of a full implementation. I know that the actual implementation shouldn't be any longer than this because it just takes the input and compares it against the regex.
match returns the match (a re.Match object) or None if the expression doesn't match. If you want to return a boolean whether the regex matches, you probably want to use pattern.match(inputString) is not None

Using a list of strings in an if statement [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 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)

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