How can I remove multiple characters in a list? - python

Having such list:
x = ['+5556', '-1539', '-99','+1500']
How can I remove + and - in nice way?
This works but I'm looking for more pythonic way.
x = ['+5556', '-1539', '-99', '+1500']
n = 0
for i in x:
x[n] = i.replace('-','')
n += 1
n = 0
for i in x:
x[n] = i.replace('+','')
n += 1
print x
Edit
+ and - are not always in leading position; they can be anywhere.

Use string.translate(), or for Python 3.x str.translate:
Python 2.x:
>>> import string
>>> identity = string.maketrans("", "")
>>> "+5+3-2".translate(identity, "+-")
'532'
>>> x = ['+5556', '-1539', '-99', '+1500']
>>> x = [s.translate(identity, "+-") for s in x]
>>> x
['5556', '1539', '99', '1500']
Python 2.x unicode:
>>> u"+5+3-2".translate({ord(c): None for c in '+-'})
u'532'
Python 3.x version:
>>> no_plus_minus = str.maketrans("", "", "+-")
>>> "+5-3-2".translate(no_plus_minus)
'532'
>>> x = ['+5556', '-1539', '-99', '+1500']
>>> x = [s.translate(no_plus_minus) for s in x]
>>> x
['5556', '1539', '99', '1500']

Use str.strip() or preferably str.lstrip():
In [1]: x = ['+5556', '-1539', '-99','+1500']
using list comprehension:
In [3]: [y.strip('+-') for y in x]
Out[3]: ['5556', '1539', '99', '1500']
using map():
In [2]: map(lambda x:x.strip('+-'),x)
Out[2]: ['5556', '1539', '99', '1500']
Edit:
Use the str.translate() based solution by #Duncan if you've + and - in between the numbers as well.

x = [i.replace('-', "").replace('+', '') for i in x]

string.translate() will only work on byte-string objects not unicode. I would use re.sub:
>>> import re
>>> x = ['+5556', '-1539', '-99','+1500', '45+34-12+']
>>> x = [re.sub('[+-]', '', item) for item in x]
>>> x
['5556', '1539', '99', '1500', '453412']

These functions clean a list of strings of undesired characters.
lst = ['+5556', '-1539', '-99','+1500']
to_be_removed = "+-"
def remove(elem, to_be_removed):
""" Remove characters from string"""
return "".join([char for char in elem if char not in to_be_removed])
def clean_str(lst, to_be_removed):
"""Clean list of strings"""
return [remove(elem, to_be_removed) for elem in lst]
clean_str(lst, to_be_removed)
# ['5556', '1539', '99', '1500']

basestr ="HhEEeLLlOOFROlMTHEOTHERSIDEooEEEEEE"
def replacer (basestr, toBeRemove, newchar) :
for i in toBeRemove :
if i in basestr :
basestr = basestr.replace(i, newchar)
return basestr
newstring = replacer(basestr,['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'], "")
print(basestr)
print(newstring)
Output :
HhEEeLLlOOFROlMTHEOTHERSIDEooEEEEEE
helloo

Related

Getting the nth char of each string in a list of strings

Let's they I have the list ['abc', 'def', 'gh'] I need to get a string with the contents of the first char of the first string, the first of the second and so on.
So the result would look like this: "adgbehcf" But the problem is that the last string in the array could have two or one char.
I already tried to nested for loop but that didn't work.
Code:
n = 3 # The encryption number
for i in range(n):
x = [s[i] for s in partiallyEncrypted]
fullyEncrypted.append(x)
a version using itertools.zip_longest:
from itertools import zip_longest
lst = ['abc', 'def', 'gh']
strg = ''.join(''.join(item) for item in zip_longest(*lst, fillvalue=''))
print(strg)
to get an idea why this works it may help having a look at
for tpl in zip_longest(*lst, fillvalue=''):
print(tpl)
I guess you can use:
from itertools import izip_longest
l = ['abc', 'def', 'gh']
print "".join(filter(None, [i for sub in izip_longest(*l) for i in sub]))
# adgbehcf
Having:
l = ['abc', 'def', 'gh']
This would work:
s = ''
In [18]: for j in range(0, len(max(l, key=len))):
...: for elem in l:
...: if len(elem) > j:
...: s += elem[j]
In [28]: s
Out[28]: 'adgbehcf'
Please don't use this:
''.join(''.join(y) for y in zip(*x)) +
''.join(y[-1] for y in x if len(y) == max(len(j) for j in x))

Replace in strings of list

I can use re.sub easily in single string like this:
>>> a = "ajhga':&+?%"
>>> a = re.sub('[.!,;+?&:%]', '', a)
>>> a
"ajhga'"
If I use this on list of strings then I am not getting the result. What I am doing is:
>>> a = ["abcd:+;", "(l&'kka)"]
>>> for x in a:
... x = re.sub('[\(\)&\':+]', '', x)
...
>>> a
['abcd:+;', "(l&'kka)"]
How can I strip expressions from strings in list?
>>> a = ["abcd:+;", "(l&'kka)"]
>>> a = [re.sub('[\(\)&\':+]', '', x) for x in a]
>>> a
['abcd;', 'lkka']
>>>
for index,x in enumerate(a):
a[index] = re.sub('[\(\)&\':+]', '', x)
Your changing the value but not updating your list. enumerate is function that return tuple (index,value) for each item of list

Python - parsing a string with letters and numbers not blocked together

I'm having trouble parsing out a string that contains letters and numbers and getting a list back. For example:
>>> s = '105Bii2016'
>>> foo(s)
['105', 'Bii', '2016']
Right now I can only do it if the numbers are together:
def foo(s):
num, letter = '', ''
for i in s:
if i.isdigit():
num += i
else:
letter += i
return [letter, num]
And when I call this:
>>> s = '1234gdfh1234'
>>> foo(s)
['gdfh', '12341234']
How about itertools.groupby:
>>> s = '1234gdfh1234'
>>> from itertools import groupby
>>> print [''.join(v) for k,v in groupby(s,str.isdigit)]
['1234', 'gdfh', '1234']
Another solution uses regex:
>>> print [x for x in re.split(r'(\d+)',s) if x]
['1234', 'gdfh', '1234']
>>> from re import split
>>> s = '1234gdfh1234'
>>> [i for i in split(r'(\d+)',s) if i]
['1234', 'gdfh', '1234']

How to convert list into string with quotes in python

i have a list and want it as a string with quotes
mylist = [1,2,3]
require O/P as
myString = "'1','2','3'"
i tried mystring = '\',\''.join(mylist)
it gave me result as
mystring = "1','2','3"
first and last quotes (') are missing
This seems to be the only solution so far that isn't a hack...
>>> mylist = [1,2,3]
>>> ','.join("'{0}'".format(x) for x in mylist)
"'1','2','3'"
This can also be written more compactly as:
>>> ','.join(map("'{0}'".format, mylist))
"'1','2','3'"
Or, using an f-string:
>>> mylist = [1,2,3]
>>> ','.join(f"'{x}'" for x in mylist)
"'1','2','3'"
>>> mylist = [1,2,3]
>>> str([str(x) for x in mylist]).strip("[]")
"'1','2','3'"
as a simple hack, why don't you..
mystring = "'%s'" %"','".join(mylist)
wrap the result of your commands in quotes?
you can do this as well
mylist = [1, 2, 3]
mystring = str(map(str, mylist)).strip("[]")
OR regular repr:
>>> l=[1,2,3]
>>> ','.join(repr(str(i)) for i in l)
"'1','2','3'"
>>>

Pythonic way to build a Combination String

I have one list, like so,
a = ['dog','cat','mouse']
I want to build a list that is a combination of the all the list elements and looks like,
ans = ['cat-dog', 'cat-mouse','dog-mouse']
This is what I came up with,
a = ['dog','cat','mouse']
ans = []
for l in (a):
t= [sorted([l,x]) for x in a if x != l]
ans.extend([x[0]+'-'+x[1] for x in t])
print list(set(sorted(ans)))
Is there a simpler and a more pythonic way!
How important is the ordering?
>>> a = ['dog','cat','mouse']
>>> from itertools import combinations
>>> ['-'.join(el) for el in combinations(a, 2)]
['dog-cat', 'dog-mouse', 'cat-mouse']
Or, to match your example:
>>> ['-'.join(el) for el in combinations(sorted(a), 2)]
['cat-dog', 'cat-mouse', 'dog-mouse']
The itertools module:
>>> import itertools
>>> map('-'.join, itertools.combinations(a, 2))
['dog-cat', 'dog-mouse', 'cat-mouse']
itertools is surely the way to go here. If you want to do it only with build-ins, use:
a = ['dog','cat','mouse']
ans = [x + '-' + y for x in a for y in a if x < y]

Categories

Resources