This question already has answers here:
How can I find all common letters in a set of strings?
(2 answers)
Closed 8 years ago.
I need to make a function that takes two string arguments and returns a string with only the characters that are in both of the argument strings. There should be no duplicate characters in the return value.
this is what I have but I need to make it print things only once if there is more then one
def letter(x,z):
for i in x:
for f in z:
if i == f:
s = str(i)
print(s)
If the order is not important, you can take the intersection & of the set of characters in each word, then join that set into a single string and return it.
def makeString(a, b):
return ''.join(set(a) & set(b))
>>> makeString('sentence', 'santa')
'nts'
Try this
s = set()
def letter(x,z):
for i in x:
for f in z:
if i == f:
s.add(i)
letter("hello","world")
print("".join(s))
It will print 'ol'
If sets aren't your bag for some reason (perhaps you want to maintain the order in one or other of the strings, try:
def common_letters(s1, s2):
unique_letters = []
for letter in s1:
if letter in s2 and letter not in unique_letters:
unique_letters.append(letter)
return ''.join(unique_letters)
print(common_letters('spam', 'arthuprs'))
(Assuming Python 3 for the print()).
Related
This question already has answers here:
Capitalise every other letter in a string in Python? [closed]
(5 answers)
Closed 3 years ago.
I want the program to return ' mahir ' as 'MaHiR', I have got MHR but how do I get 'a' and 'h' at their usual place ?
I have already tried slicing but that does not work
s = 'mahir'
a = list (s)
c = a[0:5:2]
for i in range (len(c)):
print (c[i].capitalize(),end = " ")
Python's strings are immutable, calling c[i].capitalize() will not change c[i], and therefore will not change s, to modify a string you must create a new one out of it, you can use str.join with a generator expression instead:
s = 'mahir'
s = ''.join(c.upper() if i % 2 == 0 else c for i, c in enumerate(s))
print(s)
Output:
MaHiR
If you want to do it using slicing, you could convert your string to a list since lists are mutable (but the string approach above is better):
s = 'mahir'
l = list(s)
l[::2] = map(str.upper, l[::2])
s = ''.join(l)
print(s)
Output:
MaHiR
This question already has answers here:
How do I compare version numbers in Python?
(16 answers)
Closed 6 years ago.
I want to get the maximum value from a list.
List = ['1.23','1.8.1.1']
print max(List)
If I print this I'm getting 1.8.1.1 instead of 1.23.
What I am doing wrong?
The easiest way is, to use tuple comparison.
Say:
versions = ['1.23','1.8.1.1']
def getVersionTuple(v):
return tuple(map(int, v.strip().split('.')))
Now you can use, print(max(map(getVersionTuple, versions))) to get the maximum.
EDIT:
You can use '.'.join(map(str, m)) to get the original string (given m holds the max tuple).
These aren't numbers, they are strings, and as such they are sorted lexicographically. Since the character 8 comes after 2, 1.8.1.1 is returned as the maximum.
One way to solve this is to write your own comparing function which takes each part of the string as an int and compares them numerically:
def version_compare(a, b):
a_parts = a.split('.')
b_parts = b.split('.')
a_len = len(a_parts)
b_len = len(b_parts)
length = min(a_len, b_len)
# Compare the parts one by one
for i in range(length):
a_int = int(a_parts[i])
b_int = int(b_parts[i])
# And return on the first nonequl part
if a_int != b_int:
return a_int - b_int
# If we got here, the longest list is the "biggest"
return a_len - b_len
print sorted(['1.23','1.8.1.1'], cmp=version_compare, reverse=True)[0]
A similar approach - assuming these strings are version numbers - is to turn the version string to an integer list:
vsn_list=['1.23', '1.8.1.1']
print sorted( [ [int(v) for v in x.split(".")] for x in vsn_list ] )
When you compare strings, they are compared character by character so any string starting with '2' will sort before a string starting with '8' for example.
This question already has answers here:
Remove char at specific index - python
(8 answers)
Closed 2 months ago.
I'm removing an char from string like this:
S = "abcd"
Index=1 #index of string to remove
ListS = list(S)
ListS.pop(Index)
S = "".join(ListS)
print S
#"acd"
I'm sure that this is not the best way to do it.
EDIT
I didn't mentioned that I need to manipulate a string size with length ~ 10^7.
So it's important to care about efficiency.
Can someone help me. Which pythonic way to do it?
You can bypass all the list operations with slicing:
S = S[:1] + S[2:]
or more generally
S = S[:Index] + S[Index + 1:]
Many answers to your question (including ones like this) can be found here: How to delete a character from a string using python?. However, that question is nominally about deleting by value, not by index.
Slicing is the best and easiest approach I can think of, here are some other alternatives:
>>> s = 'abcd'
>>> def remove(s, indx):
return ''.join(x for x in s if s.index(x) != indx)
>>> remove(s, 1)
'acd'
>>>
>>>
>>> def remove(s, indx):
return ''.join(filter(lambda x: s.index(x) != 1, s))
>>> remove(s, 1)
'acd'
Remember that indexing is zero-based.
You can replace the Index character with "".
str = "ab1cd1ef"
Index = 3
print(str.replace(str[Index],"",1))
def missing_char(str, n):
n = abs(n)
front = str[:n] # up to but not including n
back = str[n+1:] # n+1 through end of string
return front + back
S = "abcd"
Index=1 #index of string to remove
S = S.replace(S[Index], "")
print(S)
I hope it helps!
This question already has answers here:
Python analog of PHP's natsort function (sort a list using a "natural order" algorithm) [duplicate]
(3 answers)
Is there a built in function for string natural sort?
(23 answers)
Closed 8 years ago.
Hello all. i am learning python recently.
I am having a problem sorting files in numerical order. i have files in order in list:
["1card.txt", "card.txt" , "3card.txt", "52card.txt", "badcard.txt"]
when i simply print the list it doesn't print in order instead it prints: 1card.txt, 10card.txt and so on. so how do i fixed the following code?
file=glob.glob('/directory/*.txt')
sorted(file, key=int)
How about:
import re
def tryint(s):
try:
return int(s)
except ValueError:
return s
def alphanum_key(s):
return [tryint(c) for c in re.split('([0-9]+)', s)]
def sort_nicely(l):
return sorted(l, key=alphanum_key)
Then you could do:
>>> file = ["1card.txt", "card.txt" , "3card.txt", "52card.txt", "badcard.txt"]
>>> sort_nicely(file)
['1card.txt', '3card.txt', '52card.txt', 'badcard.txt', 'card.txt']
A simple solution without regular expression could be:
def sort_int(examp):
pos = 1
while examp[:pos].isdigit():
pos += 1
return examp[:pos-1] if pos > 1 else examp
sorted(files, key=sort_int)
['1card.txt', '3card.txt', '52card.txt', 'badcard.txt', 'card.txt']
files = ["1card.txt", "card.txt" , "3card.txt", "52card.txt", "badcard.txt"]
def nat_sort(s):
'''
provides a sort mechanism for strings that may or
may not lead with an integer
'''
for i, c in enumerate(s):
if not c.isdigit():
break
if not i:
return 0, s
else:
return int(s[:i]), s[i:]
files.sort(key=nat_sort)
And now files is a sorted list:
['badcard.txt', 'card.txt', '1card.txt', '3card.txt', '52card.txt']
To sort keeping the similar letters together, do similarly to above:
def nat_sort(s):
'''
provides a sort mechanism for strings that may or
may not lead with an integer, but groups by strings
starting after integers, if any
'''
for i, c in enumerate(s):
if not c.isdigit():
break
if not i:
return s, 0
else:
return s[i:], int(s[:i])
files.sort(key=nat_sort)
And now files returns:
['badcard.txt', 'card.txt', '1card.txt', '3card.txt', '52card.txt']
This question already has answers here:
Removing elements that have consecutive duplicates
(9 answers)
Closed 3 years ago.
For a string such as '12233322155552', by removing the duplicates, I can get '1235'.
But what I want to keep is '1232152', only removing the consecutive duplicates.
import re
# Only repeated numbers
answer = re.sub(r'(\d)\1+', r'\1', '12233322155552')
# Any repeated character
answer = re.sub(r'(.)\1+', r'\1', '12233322155552')
You can use itertools, here is the one liner
>>> s = '12233322155552'
>>> ''.join(i for i, _ in itertools.groupby(s))
'1232152'
Microsoft / Amazon job interview type of question:
This is the pseudocode, the actual code is left as exercise.
for each char in the string do:
if the current char is equal to the next char:
delete next char
else
continue
return string
As a more high level, try (not actually the implementation):
for s in string:
if s == s+1: ## check until the end of the string
delete s+1
Hint: the itertools module is super-useful. One function in particular, itertools.groupby, might come in really handy here:
itertools.groupby(iterable[, key])
Make an iterator that returns consecutive keys and groups from
the iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the iterable
needs to already be sorted on the same key function.
So since strings are iterable, what you could do is:
use groupby to collect neighbouring elements
extract the keys from the iterator returned by groupby
join the keys together
which can all be done in one clean line..
First of all, you can't remove anything from a string in Python (google "Python immutable string" if this is not clear).
M first approach would be:
foo = '12233322155552'
bar = ''
for chr in foo:
if bar == '' or chr != bar[len(bar)-1]:
bar += chr
or, using the itertools hint from above:
''.join([ k[0] for k in groupby(a) ])
+1 for groupby. Off the cuff, something like:
from itertools import groupby
def remove_dupes(arg):
# create generator of distinct characters, ignore grouper objects
unique = (i[0] for i in groupby(arg))
return ''.join(unique)
Cooks for me in Python 2.7.2
number = '12233322155552'
temp_list = []
for item in number:
if len(temp_list) == 0:
temp_list.append(item)
elif len(temp_list) > 0:
if temp_list[-1] != item:
temp_list.append(item)
print(''.join(temp_list))
This would be a way:
def fix(a):
list = []
for element in a:
# fill the list if the list is empty
if len(list) == 0:list.append(element)
# check with the last element of the list
if list[-1] != element: list.append(element)
print(''.join(list))
a= 'GGGGiiiiniiiGinnaaaaaProtijayi'
fix(a)
# output => GiniGinaProtijayi
t = '12233322155552'
for i in t:
dup = i+i
t = re.sub(dup, i, t)
You can get final output as 1232152