Splitting and then removing last character in comprehension - python

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()]

Related

How to append strings with tab characters to a list and print them also with tab characters?

I want to append a string with a tab character to a list. Then, when I print the list, I want to be able to get the same output when I do the print(string).
For example:
list1 = []
string = "Names:\tLucas"
print(list1)
print(string)
The output:
['Names\tLucas']
Names Lucas
What's a way to do this.
You will have to print the list items themselves, instead of the list.
By iteration:
>>> list1 = []
>>> string1 = "Names:\tLucas"
>>> string2 = "Names:\tJohn"
>>>
>>> list1.append(string1)
>>> list1.append(string2)
>>>
>>> for item in list1:
... print(item)
...
Names: Lucas
Names: John
By unpacking the list:
>>> list1 = []
>>> string1 = "Names:\tLucas"
>>> string2 = "Names:\tJohn"
>>>
>>> list1.append(string1)
>>> list1.append(string2)
>>>
>>> print(*list1, sep='\n')
Names: Lucas
Names: John
try something like this
print("{}".format(string))

Join characters from list of strings by index

For example, I have the following list.
list=['abc', 'def','ghi','jkl','mn']
I want to make a new list as:
newList=['adgjm','behkn','cfil']
picking every first character of each element forming a new string then appending into the new list, and then with the second character of every element and so on:
Thanks for the help.
One way is zipping the strings in the list, which will interleave the characters from each string in the specified fashion, and join them back with str.join:
l = ['abc', 'def','ghi','jkl']
list(map(''.join, zip(*l)))
# ['adgj', 'behk', 'cfil']
For strings with different length, use zip_longest, and fill with an empty string:
from itertools import zip_longest
l = ['abcZ', 'def','ghi','jkl']
list(map(''.join, zip_longest(*l, fillvalue='')))
# ['adgj', 'behk', 'cfil', 'Z']
You can try this way:
>>> list1 =['abc', 'def','ghi','jkl']
>>> newlist = []
>>> for args in zip(*list1):
... newlist.append(''.join(args))
...
>>> newlist
['adgj', 'behk', 'cfil']
Or using list comprehension:
>>> newlist = [''.join(args) for args in zip(*list1)]
>>> newlist
['adgj', 'behk', 'cfil']
You can try this:
list=['abc', 'def','ghi','jkl']
n = len(list[0])
newList = []
i = 0
for i in range(n):
newword = ''
for word in list:
newword += word[i]
newList.append(newword)
print(newList)

Python trigrams to tuple

I have a trigram like
trigrm = [((w1,tag1), (w2,tag2),(w3,tag3))]
I would like to extract only tags of each word from above trigram in a tuple like
tup = (tag1,tag2,tag3)
ll = [x for _,x in sum(ll,())]
You can try:
>>> trigrm = [(("w1","tag1"), ("w2","tag2"),("w3","tag3"))]
>>> output = ([x[1] for x in trigrm[0]])
>>> print output
['tag1', 'tag2', 'tag3']
>>> tuple(output)
('tag1', 'tag2', 'tag3')
You can use zip. Here is an example using strings because I don't know the variable values
trigrm = [(('w1','tag1'), ('w2','tag2'),('w3','tag3'))]
tuples = list(zip(*trigrm[0]))[1]
print (tuples)
# ('tag1', 'tag2', 'tag3')

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

Categories

Resources