Replace in strings of list - python

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

Related

Splitting and then removing last character in comprehension

I am trying to write a comprehension in python to split a string and then remove the last character in each of the elements in the resulting list, for example:
>>> text = "firstX secondY thirdZ"
>>> split_text = < some code >
>>> print(split_text)
['first','second','third']
I can get it to do what I want without a comprehension:
>>> text = "firstX secondY thirdZ"
>>> split_text = []
>>> for temp in text.split():
... split_text.append(temp[:-1])
...
>>> print(split_text)
['first', 'second', 'third']
but I would like to learn how to do it in a single comprehension..
Try the below
text = "firstX secondY thirdZ"
text_lst = [x[:-1] for x in text.split(' ')]
print(text_lst)
output
['first', 'second', 'third']
You could do:
splittext = [x[:-1] for x in text.split()]

Create a list of consequential alphanumeric elements

I have
char=str('DOTR')
and
a=range(0,18)
How could I combine them to create a list with:
mylist=['DOTR00','DOTR01',...,'DOTR17']
If I combine them in a for loop then I lose the leading zero.
Use zfill:
>>> string = "DOTR"
>>> for i in range(0, 18):
... print("DOTR{}".format(str(i).zfill(2)))
...
DOTR00
DOTR01
DOTR02
DOTR03
DOTR04
DOTR05
DOTR06
DOTR07
DOTR08
DOTR09
DOTR10
DOTR11
DOTR12
DOTR13
DOTR14
DOTR15
DOTR16
DOTR17
>>>
And if you want a list:
>>> my_list = ["DOTR{}".format(str(i).zfill(2)) for i in range(18)]
>>> my_list
['DOTR00', 'DOTR01', 'DOTR02', 'DOTR03', 'DOTR04', 'DOTR05', 'DOTR06', 'DOTR07', 'DOTR08', 'DOTR09', 'DOTR10', 'DOTR11', 'DOTR12', 'DOTR13', 'DOTR14', 'DOTR15', 'DOTR16', 'DOTR17']
>>>
You can do it using a list comprehension like so:
>>> mylist = [char+'{0:02}'.format(i) for i in a]
>>> mylist
['DOTR00', 'DOTR01', 'DOTR02', 'DOTR03', 'DOTR04', 'DOTR05', 'DOTR06', 'DOTR07', 'DOTR08', 'DOTR09', 'DOTR10', 'DOTR11', 'DOTR12', 'DOTR13', 'DOTR14', 'DOTR15', 'DOTR16', 'DOTR17']
Simply use list comprehension and format:
mylist = ['DOTR%02d'%i for i in range(18)]
Or given that char and a are variable:
mylist = ['%s%02d'%(char,i) for i in a]
You can, as #juanpa.arrivillaga also specify it as:
mylist = ['{}{:02d}'.format(char,i) for i in a]
List comprehension is a concept where you write an expression:
[<expr> for <var> in <iterable>]
Python iterates over the <iterable> and unifies it with <var> (here i), next it calls the <expr> and the result is appended to the list until the <iterable> is exhausted.
can do like this
char = str('DOTR')
a=range(0,18)
b = []
for i in a:
b.append(char + str(i).zfill(2))
print(b)

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'"
>>>

Change array that might contain None to an array that contains "" in python

I have a python function that gets an array called row.
Typically row contains things like:
["Hello","goodbye","green"]
And I print it with:
print "\t".join(row)
Unfortunately, sometimes it contains:
["Hello",None,"green"]
Which generates this error:
TypeError: sequence item 2: expected string or Unicode, NoneType found
Is there an easy way to replace any None elements with ""?
You can use a conditional expression:
>>> l = ["Hello", None, "green"]
>>> [(x if x is not None else '') for x in l]
['Hello', '', 'green']
A slightly shorter way is:
>>> [x or '' for x in l]
But note that the second method also changes 0 and some other objects to the empty string.
You can use a generator expression in place of the array:
print "\t".join(fld or "" for fld in row)
This will substitute the empty string for everything considered as False (None, False, 0, 0.0, ''…).
You can also use the built-in filter function:
>>> l = ["Hello", None, "green"]
>>> filter(None, l)
['Hello', 'green']

Categories

Resources