This question already has answers here:
Determine prefix from a set of (similar) strings
(11 answers)
Closed 5 years ago.
If I have two strings, how can I find the index where the string stops matching?
'abcdefghijk' and the false alphabet 'abcdxyz', I know they stop matching at index 4, but how can I output that in a function setting?
Use the enumerate() function to find the index, for which the letter in the second string does not match the current letter in the first string -
def matcher(str1, str2):
for idx, item in enumerate(str1):
if item != str2[idx]:
return idx
return -1 # if no differing letter in second string
print(matcher('abcdefghijk', 'abcdxyz')) # 4
Using some simple comparisons of sliced strings:
We can create a simple function that keeps slicing the strings till it reaches the end of the first string and compares them:
def match(s1, s2):
for i in range(len(s1)+1):
if s1[:i] != s2[:i]:
return i - 1
return -1
and some tests:
>>> match('abcdefghijk', 'abcdxyz')
4
>>> match('124', '123')
2
>>> match('123456', '123abc')
3
>>> match("abcdef", "abcdef")
-1
Related
This question already has answers here:
What does enumerate() mean?
(7 answers)
Closed 12 months ago.
list = []
word = 'hello'
for i in word:
list.append(i)
for i in list:
print(list.index(i))
output:
0 1 2 2 4
I dont know how to make the second 'l' to have an index of 3 instead of 2. rindex() does not work on for the code that I am making
Since you're printing just the list indexes which (by definition) are 0 1 2 3 4, you could use a simple range() loop:
for i in range(len(mylist)):
print(i)
The index() method returns the position at the first occurrence of the specified value.
To have the index of all the elements you can do like this
_list = []
word = 'hello'
for i in word:
_list.append(i)
for i in range(len(_list)):
print(_list[i], _list.index(_list[i], i))
This question already has answers here:
Search strings in list containing specific letters in random order
(5 answers)
Closed 4 years ago.
I need to find if a string has all characters of a substring. So for a 7 char string i want to know if the chars of a 5 char substings are in the string, without repeating letters (if substring has 2 letters a, then the string needs at max 2 letters a).
For exemple :
Substring = 'aabfy'
String1 = 'aabcfgy'
String2 = 'abcfgmy'
String3 = 'aaabcfy'
Then String1 and String3 are True, but String2 is False. Because sub string is in 1 and 3 but not in 2 (double a, but it can also be any other letter).
I hope i explained myself, any questions i can and will answer.
You can use collections.Counter in the following way:
from collections import Counter
def contains_all(string, substring):
c1, c2 = Counter(string), Counter(substring)
return all(c1[x] >= c2[x] for x in c2)
This will ensure every character in the substring is at least as many times in the containing string.
>>> contains_all('aaabcfy', 'aabfy')
True
>>> contains_all('abcfgmy', 'aabfy')
False
>>> contains_all('aabcfgy', 'aabfy')
True
Update: A better version (thx to #HenadziRabkin for the hint), using Counter difference:
def contains_all(string, substring):
return not (Counter(substring) - Counter(string))
self.cs = Counter(source)
# more efficient version
def countains_all(target):
ct = Counter(target)
for k,v in ct.items(): # Compare only target symbols
if k not in self.cs or self.cs[k]- v < 0: # Break comparison if a source has number of expected symbol types less than a target
return False
return True
Or use str.count in list comprehension, with all:
def f(s):
return all(s.count(i)>=Substring.count(i) for i in Substring)
print(f(String1))
print(f(String2))
print(f(String3))
Output:
True
False
True
This question already has answers here:
Understanding slicing
(38 answers)
Closed 4 years ago.
Say I have a list arr and an index i within [0:len(arr)], how do I get all the elements starting from arr[i] up to arr[-1] in a Pythonic way?
For example:
arr = 'abcdef'
i = 3
I basically want to get b = 'def'
I tried
b = a[i:-1]
but obviously that'll leave out the last element.
Also, my list sometimes has only 1 element, so i = 0. How do I safely treat that edge case?
Thank you!
You could use python list slicing like this:
b = arr[i:] # This prints 'def' when arr = 'abcdef' and i = 3
This will print everything from the ith position to the end. And if i is greater than the string length, it'll print an empty string.
This question already has answers here:
Pythonic way to count the number of trailing zeros in base 2
(5 answers)
Closed 5 years ago.
I have a series of strings like:
my_text = "one? two three??"
I want to count only the number of ? at the end of the string. The above should return 2 (rather than 3).
What I've tried so far:
my_text.count("?") # returns 3
There's not a built-in method for it. But something simple like this should do the trick:
>>> len(my_text) - len(my_text.rstrip('?'))
2
You could also use a regexp to count the number of trailing question marks :
import re
def count_trailing_question_marks(text):
last_question_marks = re.compile("\?*$")
return len(last_question_marks.search(text).group(0))
print count_trailing_question_marks("one? two three??")
# 2
print count_trailing_question_marks("one? two three")
# 0
Not so clean but simple way:
my_text = "one? two three??"
total = 0
question_mark = '?'
i = 0
for c in my_text:
i -= 1
if my_text[i] == question_mark:
total += 1
else:
break
One-liner using my favourite itertools:
First reverse the string, then continue iterating (taking the values) while our condition is satisfied (value == '?'). This returns an iterable which we exhaust into a list and finally take its length.
len(list(itertools.takewhile(lambda x:x=='?',reversed(my_text))))
This question already has answers here:
How do I count the occurrences of a list item?
(30 answers)
Closed 9 years ago.
I need help:
I want to write function that: takes a list as a input and return count of specific string.
If function input is x=[a,a,b,c] function need return 2 (a is two times in this list).
>>> def F(seq, string):
return seq.count(string)
>>> F(['a','a','b','c'], 'a')
2
Equivalent to:
def F(seq, string):
n = 0
for x in seq:
if x == string:
n += 1
return n