Create a string from a list using list comprehension - python-3.x

I am trying to create a string separated by comma from the below given list
['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']
New string should contain only the filename like below which is separated by comma
'aaa.xlsx,bbb.xlsx,ccc.xlsx'
I have achieved this using the below code
n = []
for p in input_list:
l = p.split('\\')
l = l[len(l)-1]
n.append(l)
a = ','.join(n)
print(a)
But instead of using multiple lines of code i would like to achieve this in single line using a list comprehension or regular expression.
Thanks in advance...

Simply do a
main_list = ['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']
print([x.split("\\")[-1] for x in main_list])
OUTPUT:
['aaa.xlsx', 'bbb.xlsx', 'ccc.xlsx']
In case u want to get the string of this simply do a
print(",".join([x.split("\\")[-1] for x in main_list]))
OUTPUT:
aaa.xlsx,bbb.xlsx,ccc.xlsx
Another way to do the same is:
print(",".join(map(lambda x : x.split("\\")[-1],main_list)))
OUTPUT:
aaa.xlsx,bbb.xlsx,ccc.xlsx
Do see that os.path.basename is OS-dependent and may create problems on cross-platform scripts.

Using os.path.basename with str.join
Ex:
import os
data = ['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']
print(",".join(os.path.basename(i) for i in data))
Output:
aaa.xlsx,bbb.xlsx,ccc.xlsx

Related

How to insert variable length list into string

I have what I think is a basic question in Python:
I have a list that can be variable in length and I need to insert it into a string for later use.
Formatting is simple, I just need a comma between each name up to nameN and parenthesis surrounding the names.
List = ['name1', 'name2' .... 'nameN']
string = "Their Names are <(name1 ... nameN)> and they like candy.
Example:
List = ['tom', 'jerry', 'katie']
print(string)
Their Names are (tom, jerry, katie) and they like candy.
Any ideas on this? Thanks for the help!
# Create a comma-separated string with names
the_names = ', '.join(List) # 'tom, jerry, katie'
# Interpolate it into the "main" string
string = f"Their Names are ({the_names}) and they like candy."
There are numerous ways to achieve that.
You could use print + format + join similar to the example from #ForceBru.
Using format would make it compatible with both Python2 and Python3.
names_list = ['tom', 'jerry', 'katie']
"""
Convert the list into a string with .join (in this case we are separating with commas)
"""
names_string = ', '.join(names_list)
# names_string == "tom, katie, jerry"
# Now add one string inside the other:
string = "Their Names are ({}) and they like candy.".format(names_string)
print(string)
>> Their Names are (tom, jerry, katie) and they like candy.

Replace/Remove colons of Strings inside a list

Simple question:
I got following List:
['nordhessen:abfall_b', 'nordhessen:anschlussstelle_b']
And I want to get this List:
['nordhessenabfall_b', 'nordhessenanschlussstelle_b']
How do I remove the colons?
data = ['nordhessen:abfall_b', 'nordhessen:anschlussstelle_b']
new_data = [item.replace(':', '') for item in data]

How can I sort the input string "DC501GCCCA098911" as to OutPut: "CD015ACCCG011899" using Python3?

How can I sort the input string "DC501GCCCA098911" as to outPut: "CD015ACCCG011899" using Python3 ?
Based on the limited information. I'm going to assume it's split on alpha/numeric boundaries:
from re import split
inp = "DC501GCCCA098911"
out = ''.join(''.join(sorted(list(sub))) for sub in split(r"([A-Z]+|[0-9]+)", inp) if sub)
print(out) // Prints CD015ACCCG011899
In a nutshell this creates a regular expression that creates groups of strings that are all letters or numbers, then creates a list out of each group, sorts it, and joins it all back together.

How to add single quote to values in list?

Here is my list
x = ['India,America,Australia,Japan']
How to convert above list into
x = ['India','America','Australia','Japan']
I tried it using strip and split method but it doesn't work.
You can turn that list into the string and split in commas:
test = ['India,America,Australia,Japan']
result = "".join(test).split(",")
print(result)
Output is this:
['India', 'America', 'Australia', 'Japan']
or you can use regex library.
import re
x = "".join(['India,America,Australia,Japan'])
xText = re.compile(r"\w+")
mo = xText.findall(x)
print(mo)
The findall method looks for all the word characters and does not include comma. Finally it returns a list.
Output is this:
['India', 'America', 'Australia', 'Japan']

Python read file contents into nested list

I have this file that contains something like this:
OOOOOOXOOOO
OOOOOXOOOOO
OOOOXOOOOOO
XXOOXOOOOOO
XXXXOOOOOOO
OOOOOOOOOOO
And I need to read it into a 2D list so it looks like this:
[[O,O,O,O,O,O,X,O,O,O,O],[O,O,O,O,O,X,O,O,O,O,O],[O,O,O,O,X,O,O,O,O,O,O],[X,X,O,O,X,O,O,O,O,O,O],[X,X,X,X,O,O,O,O,O,O,O,O],[O,O,O,O,O,O,O,O,O,O,O]
I have this code:
ins = open(filename, "r" )
data = []
for line in ins:
number_strings = line.split() # Split the line on runs of whitespace
numbers = [(n) for n in number_strings]
data.append(numbers) # Add the "row" to your list.
return data
But it doesn't seem to be working because the O's and X's do not have spaces between them. Any ideas?
Just use data.append(list(line.rstrip())) list accepts a string as argument and just splits them on every character.

Resources