Cut character string every two commas - python

I would like to separate my string every both commas but I can not, can you help me.
This is what I want: ['nb1,nb2','nb3,nb4','nb5,nb6']
Here is what I did :
a= 'nb1,nb2,nb3,nb4,nb5,nb6'
compteur=0
for i in a:
if i==',' :
compteur+=1
if compteur%2==0:
print compteur
test = a.split(',', compteur%2==0 )
print a
print test
The result:
2
4
nb1,nb2,nb3,nb4,nb5,nb6
['nb1', 'nb2,nb3,nb4,nb5,nb6']
Thanks you by advances for you answers

You can use regex
In [12]: re.findall(r'([\w]+,[\w]+)', 'nb1,nb2,nb3,nb4,nb5,nb6')
Out[12]: ['nb1,nb2', 'nb3,nb4', 'nb5,nb6']

A quick fix could be to simply first separate the elements by commas and then join the elements by two together again. Like:
sub_result = a.split(',')
result = [','.join(sub_result[i:i+2]) for i in range(0,len(sub_result),2)]
This gives:
>>> result
['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
This will also work if the number of elements is odd. For example:
>>> a = 'nb1,nb2,nb3,nb4,nb5,nb6,nb7'
>>> sub_result = a.split(',')
>>> result = [','.join(sub_result[i:i+2]) for i in range(0,len(sub_result),2)]
>>> result
['nb1,nb2', 'nb3,nb4', 'nb5,nb6', 'nb7']

You use a zip operation of the list with itself to create pairs:
a = 'nb1,nb2,nb3,nb4,nb5,nb6'
parts = a.split(',')
# parts = ['nb1', 'nb2', 'nb3', 'nb4', 'nb5', 'nb6']
pairs = list(zip(parts, parts[1:]))
# pairs = [('nb1', 'nb2'), ('nb2', 'nb3'), ('nb3', 'nb4'), ('nb4', 'nb5'), ('nb5', 'nb6')]
Now you can simply join every other pair again for your output:
list(map(','.join, pairs[::2]))
# ['nb1,nb2', 'nb3,nb4', 'nb5,nb6']

Split the string by comma first, then apply the common idiom to partition an interable into sub-sequences of length n (where n is 2 in your case) with zip.
>>> s = 'nb1,nb2,nb3,nb4,nb5,nb6'
>>> [','.join(x) for x in zip(*[iter(s.split(','))]*2)]
['nb1,nb2', 'nb3,nb4', 'nb5,nb6']

Related

How to convert an integer to a list in python?

I have an integer object for example a = 1234 and I want to convert it to a list, so it would look something like [1234].
I tried converting it into a string first and then converting it to a list but that gives me [1,2,3,4].
Any suggestions?
You can just cover it in brackets.
a = 1234
print([a])
Or append()
b = []
b.append(a)
output
[1234]
Here:
a = 1234
lst = []
lst.append(a)
print(lst) #[1234]
If you are trying to convert in to string, use str()
>>> str(1234)
'1234'
If you are trying to put your int in a list, use []:
>>> var = 1234
>>> [var]
[1234]
or do:
>>> l = []
>>> l.append(var)
>>> l
[1234]
Just cover it with brackets:
a=1243
a=[a]
or create a list and append a
b = []
b.append(a) # or you could do b=[a]

How to assign two values in for loop variable

how can we use for loop to assign two values from the string like following
string="abcd"
for i in string:
print(i)
this will give i one value from the string
#output
a
b
c
d
how can i take two values like ab and cd. I know we can do this in print but i need to assign two values in "i"
I need output
#output
ab
cd
You could use list-comprehension like the following:
n = 2
s = "abcd"
res = [s[i:i+n] for i in range(0, len(s), n)]
print(res) # ['ab', 'cd']
This is applicable to any nth place.
If its only 2 chars that you are after you can also use regex, but if it for any n its not convenient, an example for n=2 is:
import re
s = "abcd"
res = re.findall('..?',s)
print(res) # ['ab', 'cd']
Try this:
string = "abcd"
for i in range(1,len(string),2):
print(string[i-1]+string[i])
Output:
ab
cd
Explanation
You can modify the range function to start at index 1 and go all the way through len(string) in steps of 2(range(1,len(string),2))
Then inside the loop, since we start index 1, we print string[i-1] and concatenate with string[i]

how to print all the elements of the split in a generic way in python

I want to print all the elements of the split- whether the result of the split is a single element list or many elements. How many the splits happen is decided on run time.
For example-
x = "abc;bcd;def"
x1 = x.split(";")
print(x1[0], x1[1], x1[2])
However, x could sometimes be - x =abc, in that case x1[1] and x1[2] would return invalid/null and it screws up my code. Is there a generic way to print the results of the split, irrespective of the number of splits that happen?
I also want to print like this-
print(blah1, x1[0], blah2)- when the split results in only one element
If split results in more than one element, it will print each additional line for the additional element-
print(blah1, x1[0], blah2) #for element0 of the split
print(blah21, x1[1], blah21) #for element1 of the split
and so on (for every additional element of the split that is generated)..
You can use str.join() to join back the split strings with whatever delimiter you want for printing. Example -
>>> x = "abc,bcd,def"
>>> x1 = x.split(',')
>>> print(' '.join(x1))
abc bcd def
Pass the list to print() as separate arguments using the *args syntax:
print(*x1)
This expands the elements, however many there are, to pass them as individual arguments to the print() function.
Just print the result of the split() call:
x = "abc;bcd;def"
x1 = x.split(";")
print x1
It will work with any number of parts:
>>> print "a;b;c".split(";")
['a', 'b', 'c']
>>> print "a;b".split(";")
['a', 'b']
>>> print "a".split(";")
['a']
>>> print "".split(";")
['']

Append two integers to list when seperated by '..' Python

If i have a list strings:
first = []
last = []
my_list = [' abc 1..23',' bcd 34..405','cda 407..4032']
how would i append the numbers flanking the .. to their corresponding lists ? to get:
first = [1,34,407]
last = [23,405,4032]
i wouldn't mind strings either because i can convert to int later
first = ['1','34','407']
last = ['23','405','4032']
Use re.search to match the numbers between .. and store them in two different groups:
import re
first = []
last = []
for s in my_list:
match = re.search(r'(\d+)\.\.(\d+)', s)
first.append(match.group(1))
last.append(match.group(2))
DEMO.
I'd use a regular expression:
import re
num_range = re.compile(r'(\d+)\.\.(\d+)')
first = []
last = []
my_list = [' abc 1..23',' bcd 34..405','cda 407..4032']
for entry in my_list:
match = num_range.search(entry)
if match is not None:
f, l = match.groups()
first.append(int(f))
last.append(int(l))
This outputs integers:
>>> first
[1, 34, 407]
>>> last
[23, 405, 4032]
One more solution.
for string in my_list:
numbers = string.split(" ")[-1]
first_num, last_num = numbers.split("..")
first.append(first_num)
last.append(last_num)
It will throw a ValueError if there is a string with no spaces in my_list or there is no ".." after the last space in some of the strings (or there is more than one ".." after the last space of the string).
In fact, this is a good thing if you want to be sure that values were really obtained from all the strings, and all of them were placed after the last space. You can even add a try…catch block to do something in case the string it tries to process is in an unexpected format.
first=[(i.split()[1]).split("..")[0] for i in my_list]
second=[(i.split()[1]).split("..")[1] for i in my_list]

Python: Joining Multiple Lists to one single Sentence

Howdy, I've got multiple lists. For example:
[u'This/ABC']
[u'is/ABC']
[u'not/ABC']
[u'even/ABC']
[u'close/ABC']
[u'to/ABC']
[u'funny/ABC']
[u'./ABC']
[u'O/ABC']
[u'noez/ABC']
[u'!/ABC']
I need to join this List to
This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC funny/ABC ./ABC
O/ABC noez/ABC !/ABC
How do I do that please? Yes, with the empty space in between!
If you put them all in a list, for example like this:
a = [
[u'This/ABC'],
[u'is/ABC'],
...
]
You can get your result by adding all the lists and using a regular join on the result:
result = ' '.join(sum(a, []))
After re-reading the question a couple of times, I suppose you also want that empty line. This is just more of the same. Add:
b = [
[u'O/ABC'],
[u'HAI/ABC'],
...
]
lines = [a, b]
result = '\n\n'.join([' '.join(sum(line, [])) for line in lines])
To join lists, try the chain function in the module itertools, For example, you can try
import itertools
print ' '.join(itertools.chain(mylist))
if the new line between the two lists are intentional, then add '\n' at the end of the first list
import itertools
a = [[u'This/ABZ'], [u'is/ABZ'], ....]
b = [[u'O/ABZ'], [u'O/noez'], ...]
a.append('\n')
print ' '.join(itertools.chain(a + b))
Easy:
x = [[u'O/ABC'], [u'noez/ABC'], [u'!/ABC']]
print ' '.join(y[0] for y in x)
If you put all your lists in one list, you can do it like this:
' '.join(e[0] for e in [[u'This/ABC'], [u'is/ABC']])

Categories

Resources