Why empty string is on every string? [duplicate] - python

This question already has answers here:
Why is True returned when checking if an empty string is in another?
(5 answers)
Closed 5 years ago.
For example:
>>> s = 'python'
>>> s.index('')
0
>>> s.index('p')
0

This is because the substring of length 0 starting at index 0 in 'python' is equal to the empty string:
>>> s[0:0]
''
Of course every substring of length zero of any string is equal to the empty string.

You can see "python" as "the empty string, followed by a p, followed by fifteen more empty strings, followed by a y, followed by forty-two empty strings, ...".
Point being, empty strings don't take any space, so there's no reason why it should not be there.
The index method could be specified like this:
s.index(t) returns a value i such that s[i : i+len(t)] is equal to t
If you substitute the empty string for t, this reads: "returns a value i such that s[i:i] is equal to """. And indeed, the value 0 is a correct return value according to this specification.

Related

Python increment to the next position in the string to search [duplicate]

This question already has answers here:
Finding multiple occurrences of a string within a string in Python [duplicate]
(19 answers)
Closed 1 year ago.
I am trying to solve for the below function. I am getting my expected empty tuple when the sub is not found in the given string 'text'. However, I am having a problem incrementing during the for-loop to find the subsequent positions of the same sub in the remainder of the string 'text'.
def findall(text,sub):
"""
Returns the tuple of all positions of substring sub in text.
If sub does not appears anywhere in text, this function returns the
empty tuple ().
Examples:
findall('how now brown cow','ow') returns (1, 5, 10, 15)
findall('how now brown cow','cat') returns ()
findall('jeeepeeer','ee') returns (1,2,5,6)
Parameter text: The text to search
Precondition: text is a string
Parameter sub: The substring to search for
Precondition: sub is a nonempty string
"""
tup = ()
for pos in range(len(text)):
if sub not in text:
tup = ()
else:
pos1 = introcs.find_str(text,sub)
tup = tup + (pos1,)
# increment to the next pos and look for the sub again, not sure how to
# move beyond the first instance of the substring in the text ???
pos1 = pos1 + 1
return tup
I think your problem will be solved easily with regular expressions best refer to this answer
but if you insist on making it your way what about you delete the substring once you find it and then the position of the next substring will be the previous one + the length of the substring something like that.
For example for findall('how now brown cow','ow') first the position is 1 we delete the susbtring we are left with 'h now brown cow','ow' then the position returned by find will be 3 + substring.length = 5 which is the actual position of the susbstring ... Try it out hope it helps

How to separate out integer and string elements from a list into two different list? [duplicate]

This question already has answers here:
Splitting List That Contains Strings and Integers
(9 answers)
Closed 5 years ago.
I want to separate out integer and string element from a list into two different list.
i.e.
list1=[1,"Red",2,"Blue",3,"Pink",4,"White",5,"Yellow"]
separate into
intList=[1,2,3,4,5]
strList=["Red","Blue","Pink","White","Yellow"]
I write this code
import string
digits=string.digits
strings=string.letters + '_' + digits
list1=[1,"Red",2,"Blue",3,"Pink",4,"White",5,"Yellow"]
number=[]
string=[]
for item in list1:
if item in digits:
number.append(item)
if item in strings:
string.append(item)
print "List of String is:",string
print "List of Digits is:",number
but it gives an error: " 'in ' requires string as left operand, not int"
How to write this program into another way?
You can make function to separate those out for you whether they be in any order
def separate(array, type):
return [n for n in array if isinstance(n, type)]
array = [ 1,"Red",2,"Blue",3,"Pink",4,"White",5,"Yellow"]
digits = separate(myList,int)
strings = array(myList,str)
print digits, strings
for further help please see
Python - Splitting List That Contains Strings and Integers

How to find the index of undetermined pattern in a string? [duplicate]

This question already has answers here:
Python Regex - How to Get Positions and Values of Matches
(4 answers)
Closed 6 years ago.
I want to find the index of multiple occurrences of at least two zeros followed by at least two ones (e.g., '0011','00011', '000111' and so on), from a string (called 'S')
The string S may look like:
'00111001100011'
The code I tried can only spot occurrences of '0011', and strangely returns the index of the first '1'. For example for the S above, my code returns 2 instead of 0:
index = []
index = [n for n in range(len(S)) if S.find('0011', n) == n]
Then I tried to use regular expression but I the regex I found can't express the specific digit I want (like '0' and '1')
Could anyone kindly come up with a solution, and tell me why my first result returns index of '1' instead of '0'? Lot's f thanks in advance!!!!!
In the following code the regex defines a single instance of the required pattern of digits. Then uses the finditer iterator of the regex to identify successive matches in the given string S. match.start() gives the starting position of each of these matches, and the entire list is returned to starts.
S = '00111001100011'
r = re.compile(r'(0{2,}1{2,})')
starts = [match.start() for match in r.finditer(S)]
print(starts)
# [0, 5, 9]

adding string ending "\" to all elements of a list of strings [duplicate]

This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Closed 6 years ago.
I have a list of strings: ['John','William','Ken','Rogers']. I need to prepend "Corp\" to each element in the list so that the final list looks like this:
['Corp\John','Corp\William','Corp\Ken','Corp\Rogers']
I tried the following:
s=['John','William','Ken','Rogers']
users=['Corp\\' + m for m in s]
print(users)
The output gives me
['Corp\\John','Corp\\William','Corp\\Ken','Corp\\Rogers']
If I try users=['Corp\' + m for m in s] I get an obvious error:
"StringError EOL while scanning string literal"
I would need each element in the exact form 'Corp\name', as this needs to be used in a for loop to validate users who are eligible to login.
This may be a problem with how you're 'outputting' the list. Using the REPL:
>>> lsa = ["Corp\{}".format(item) for item in ls]
>>> print(lsa)
['Corp\\Jenna', 'Corp\\Wilma', 'Corp\\Katie', 'Corp\\Rebecca']
>>> for i in lsa:
... print(i)
...
Corp\Jenna
Corp\Wilma
Corp\Katie
Corp\Rebecca
As you can see, in the first print, that prints the full list, we see two slashes. This is because Python is saying that the second slash is escaped. In the second print, inside a for loop, we see that there is only one slash, because we are printing each item individually and the escape string is applied, yielding only a single slash.

Select last chars of string until whitespace in Python [duplicate]

This question already has answers here:
Python: Cut off the last word of a sentence?
(10 answers)
Closed 8 years ago.
Is there any efficient way to select the last characters of a string until there's a whitespace in Python?
For example I have the following string:
str = 'Hello my name is John'
I want to return 'John'. But if the str was:
str = 'Hello my name is Sally'
I want to retrun 'Sally'
Just split the string on whitespace, and get the last element of the array. Or use rsplit() to start splitting from end:
>>> st = 'Hello my name is John'
>>> st.rsplit(' ', 1)
['Hello my name is', 'John']
>>>
>>> st.rsplit(' ', 1)[1]
'John'
The 2nd argument specifies the number of split to do. Since you just want last element, we just need to split once.
As specified in comments, you can just pass None as 1st argument, in which case the default delimiter which is whitespace will be used:
>>> st.rsplit(None, 1)[-1]
'John'
Using -1 as index is safe, in case there is no whitespace in your string.
It really depends what you mean by efficient, but the simplest (efficient use of programmer time) way I can think of is:
str.split()[-1]
This fails for empty strings, so you'll want to check that.
I think this is what you want:
str[str.rfind(' ')+1:]
this creates a substring from str starting at the character after the right-most-found-space, and up until the last character.
This works for all strings - empty or otherwise (unless it's not a string object, e.g. a None object would throw an error)

Categories

Resources