I have a list like ;
list1 = ['ex1_a','ex2_b','ex3_b']
I want to split it like this to the new list ;
newlist = ['ex1 a', 'ex2 b', 'ex3 b']
I try to do it like this but it didn't work. How can I do this?
for x in list1:
newlist = " ".join(x.split("_"))
You can use str.replace instead str.split/str.join:
list1 = ["ex1_a", "ex2_b", "ex3_b"]
newlist = [v.replace("_", " ") for v in list1]
print(newlist)
Prints:
['ex1 a', 'ex2 b', 'ex3 b']
If you want to use str.split:
newlist = [" ".join(v.split("_")) for v in list1]
Related
This question already has answers here:
How to remove leading and trailing spaces from strings in a Python list
(3 answers)
Remove trailing newline from the elements of a string list
(7 answers)
Closed 1 year ago.
How do I remove the spaces at the beginning of each string in a list?
List = [' a', ' b', ' c']
Here is what I tried, but the list remained the same:
unique_items_1 = []
for i in unique_items:
j = i.replace('^ +', '')
unique_items_1.append(j)
print(List)
My expected result was:
List = ['a', 'b', 'c']
Use str.lstrip in a list comprehension:
my_list = [' a', ' b', ' c']
my_list = [i.lstrip() for i in my_list]
print(my_list) # ['a', 'b', 'c']
To remove the leading white spaces, you can use the lstrip function.
In your case, for the list:
result = [x.lstrip() for x in List]
print(result)
For removing trailing spaces:
result = [x.rstrip() for x in List]
print(result)
The below code should work in general to remove all white spaces:
result = [x.replace(' ','') for x in List
print(result)
List = [' a',' b',' c']
print(List) # [' a', ' b', ' c']
List_Trimmed = [*map(lambda x: x.lstrip(), List)]
print(List_Trimmed) # ['a', 'b', 'c']
You can use strip():
for i in unique_items:
j = i.strip()
unique_items_1.append(j)
strip() removes spaces.
You can also use lstrip().
I have an issue with lists, I have a list lst =['ab', 'cd', 'ef']. Now I want to add a string ('are')to end of each string value of the list. I tried but it is getting added letter by letter, how to add the whole word to end of each string value in the list?
My code:
lst =['ab', 'cd', 'ef']
b = 'are'
new_list = [el1+'_'+el2 for el2 in b for el1 in lst]
It gives:
new_list = ['ab_a', 'cd_a', 'ef_a','ab_r', 'cd_r', 'ef_r','ab_e', 'cd_e', 'ef_e']
Excepted output:
new_list = ['ab_are', 'cd_are', 'ef_are']
Rather than iterate on the second string just append like
new_list = [el1+'_'+ b for el1 in lst]
Try this:
lst =['ab', 'cd', 'ef']
b = 'are'
new = ["_".join([item, b]) for item in lst]
# ['ab_are', 'cd_are', 'ef_are']
You are iterating through both list and string. Just iterate through the list:
lst =['ab', 'cd', 'ef']
b = 'are'
new_list = [el + '_' + b for el in lst]
print(new_list)
Output:
['ab_are', 'cd_are', 'ef_are']
Just iterate in list
lst = ["ab", "cd", "ef"]
b = "are"
iterated_list = [i + " " + b for i in lst]
print(iterated_list)
Another option would be the following below:
lst = ["ab", "cd", "ef"]
b = "are"
iterated_list = []
for i in lst:
iterated_list.append(i + " " + b)
print(iterated_list)
How can I turn this
list = [['I','am','a','hero'],['What','time','is','it']]
to this
list = [["I am a hero"],["What time is it"]]
This doesn't work:
list(chain.from_iterable(list.str.split(',')))
And neither does:
[a for a in list]
You could join the list items:
list1 = [['I', 'am', 'a', 'hero'], ['What', 'time', 'is', 'it']]
list2 = [[' '.join(item)] for item in list1]
print(list2)
Output:
[['I am a hero'], ['What time is it']]
Here is one way of doing it
lst = [['I','am','a','hero'],['What','time','is','it']]
new_list = [[' '.join(x)] for x in lst]
print(new_list)
How to convert
[('a',1),('b',3)]
to
[('a','1'),('b','3')]
My end goal is to get:
['a 1','b 3']
I tried:
[' '.join(col).strip() for col in [('a',1),('b',3)]]
and
[' '.join(str(col)).strip() for col in [('a',1),('b',3)]]
This ought to do it:
>>> x = [('a',1),('b',3)]
>>> [' '.join(str(y) for y in pair) for pair in x]
['a 1', 'b 3']
If you want to avoid the list comprehensions in jme's answer:
mylist = [('a',1),('b',3)]
map(lambda xs: ' '.join(map(str, xs)), mylist)
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 9 years ago.
If you had a long list of lists in the format [['A',1,2],['B',3,4]] and you wanted to combine it into ['A, 1, 2', 'B, 3, 4'] is there a easy list comprehension way to do so?
I do it like this:
this_list = [['A',1,2],['B',3,4]]
final = list()
for x in this_list:
final.append(', '.join([str(x) for x in x]))
But is this possible to be done as a one-liner?
Thanks for the answers. I like the map() based one. I have a followup question - if the sublists were instead of the format ['A',0.111,0.123456] would it be possible to include a string formatting section in the list comprehension to truncate such as to get out 'A, 0.1, 0.12'
Once again with my ugly code it would be like:
this_list = [['A',0.111,0.12345],['B',0.1,0.2]]
final = list()
for x in this_list:
x = '{}, {:.1f}, {:.2f}'.format(x[0], x[1], x[2])
final.append(x)
I solved my own question:
values = ['{}, {:.2f}, {:.3f}'.format(c,i,f) for c,i,f in values]
>>> lis = [['A',1,2],['B',3,4]]
>>> [', '.join(map(str, x)) for x in lis ]
['A, 1, 2', 'B, 3, 4']
You can use nested list comprehensions with str.join:
>>> lst = [['A',1,2],['B',3,4]]
>>> [", ".join([str(y) for y in x]) for x in lst]
['A, 1, 2', 'B, 3, 4']
>>>
li = [['A',1,2],['B',3,4],['A',0.111,0.123456]]
print [', '.join(map(str,sli)) for sli in li]
def func(x):
try:
return str(int(str(x)))
except:
try:
return '%.2f' % float(str(x))
except:
return str(x)
print map(lambda subli: ', '.join(map(func,subli)) , li)
return
['A, 1, 2', 'B, 3, 4', 'A, 0.111, 0.123456']
['A, 1, 2', 'B, 3, 4', 'A, 0.11, 0.12']