Check if string is in list with python - python-3.x

I'm new to python, and I'm trying to check if a String is inside a list.
I have these two variables:
new_filename: 'SOLICITUDES2_20201206.DAT' (str type)
and
downloaded_files:
[['SOLICITUDES-20201207.TXT'], ['SOLICITUDES-20201015.TXT'], ['SOLICITUDES2_20201206.DAT']] (list type)
for checking if the string is inside the list, I'm using the following:
if new_filename in downloaded_files:
print(new_filename,'downloaded')
and I never get inside the if.
But if I do the same, but with hard-coded text, it works:
if ['SOLICITUDES2_20201206.DAT'] in downloaded_files_list:
print(new_filename,'downloaded')
What am I doing wrong?
Thanks!

Your downloaded_files is a list of lists. A list can contain anything insider it, numbers, list, dictionaries, strings and etc. If you are trying to find if your string is inside the list, the if statement will only look for identical matches, i.e., strings.
What I suggest you do is get all the strings into a list instead of a list of lists. You can do it using list comprehension:
downloaded_files = [['SOLICITUDES-20201207.TXT'], ['SOLICITUDES-20201015.TXT'], ['SOLICITUDES2_20201206.DAT']]
downloaded_files_list = [file[0] for file in downloaded_files]
Then, your if statement should work:
new_filename = 'SOLICITUDES2_20201206.DAT'
if new_filename in downloaded_files_list:
print(new_filename,'downloaded')

Your code is asking if a string is in a list of lists of a single string each, which is why it doesn't find any.

Related

Remove list of strings from list of strings

I have a long list of strings (the main list), and a short list of strings. The short list is an exclude list, and I want to remove all occurences of the elements in the exclude list from the main list.
I've found these two ways of doing it, but none of them seem to work:
val fnrliste: MutableList<String> = ArrayList()
val excludeList = listOf("28030140259", "12050101833", "21089233132", "12050101833")
//Alternative 1:
for (fnr in excludeList) { fnrliste.remove(fnr) }
//Alternative 2:
fnrliste.removeAll(excludeList)
With both alternatives, the strings in the entries are still there when I list the contents of fnrliste.
As can be seen in this screenshot, some entries have been removed (different result with the two methods), but the first entry in the exclude list is still present:
What am I missing here?
Looks like your fnrliste contains some duplicates, so that's why you get different result. Also, as far as I can remember your screenshot, in case of removeAll the first element is "28030140259 " and not "28030140259" so everything is correct

Add single quotes around string in python

I have converted list to string.
but after conversion I am getting string without single quote around the string
for eg:
items = ['aa','bb','cc']
items = ','.join(items)
output is : aa,bb,cc
expected output: 'aa','bb','cc'
You could use a list comprehension to quote the individual strings in the list:
items = ['aa','bb','cc']
items = ','.join([f"'{i}'" for i in items])
print(items) # 'aa','bb','cc'
One way to accomplish this is by passing the list into a string formatter, which will place the outer quotes around each list element. The list is mapped to the formatter, then joined, as you have shown.
For example:
','.join(map("'{}'".format, items))
Output:
"'aa','bb','cc'"

groovy iterate through list of key and value

I have this list:
service_name_status=[a-service=INSTALL, b-service=UPGRADE, C-service=UPGRADE, D-service=INSTALL]
And I need to iterate through this list so the first element will be the value of a parameter called "SERVICE_NAME" and the second element will be the value of a parameter called "HELM_COMMAND",
after asserting those values to the parameters I will run my command that uses those parameters and then continue the next items on the list which should replace the values of the parameters with items 3 and 4 and so on.
So what I am looking for is something like that:
def service_name_status=[a-service=INSTALL, b-service=UPGRADE, C-service=UPGRADE, D-service=INSTALL]
def SERVICE_NAME
def HELM_COMMAND
for(x in service_name_status){
SERVICE_NAME=x(0,2,4,6,8...)
HELM_COMMAND=x(1,3,5,7,9...)
println SERVICE_NAME=$SERVICE_NAME
println HELM_COMMAND=$HELM_COMMAND
}
the output should be:
SERVICE_NAME=a-service
HELM_COMMAND=INSTALL
SERVICE_NAME=b-service
HELM_COMMAND=UPGRADE
SERVICE_NAME=c-service
HELM_COMMAND=UPGRADE
SERVICE_NAME=d-service
HELM_COMMAND=INSTALL
and so on...
I couldn't find anything that takes any other element in groovy, any help will be appreciated.
The collection you want is a Map, not a List.
Take note of the quotes in the map, the values are strings so you need the quotes or it won't work. You may have to change that at the source where your data comes from.
I kept your all caps variable names so you will feel at home, but they are not the convention.
Note the list iteration with .each(key, value)
This will work:
Map service_name_status = ['a-service':'INSTALL', 'b-service':'UPGRADE', 'C-service':'UPGRADE', 'D-service':'INSTALL']
service_name_status.each {SERVICE_NAME, HELM_COMMAND ->
println "SERVICE_NAME=${SERVICE_NAME}"
println "HELM_COMMAND=${HELM_COMMAND}"
}
EDIT:
The following can be used to convert that to a map. Be careful, the replaceAll part is fragile and depends on the data to always look the same.
//assuming you can have it in a string like this
String st = "[a-service=INSTALL, b-service=UPGRADE, C-service=UPGRADE, D-service=INSTALL]"
//this part is dependent on format
String mpStr = st.replaceAll(/\[/, "['")
.replaceAll(/=/, "':'")
.replaceAll(/]/, "']")
.replaceAll(/, /, "', '")
println mpStr
//convert the properly formatted string to a map
Map mp = evaluate(mpStr)
assert mp instanceof java.util.LinkedHashMap

Trim the first character from a string variable

I get a list from a website but it pulls an html tag (same first character as the role I am trying to get) along with the role. For example, I need to get the role of this user, and the role is "DeveloperContributor" but the list returns "CDeveloperContributor". I am curious to know if you can string slice like ${string}[1:]
I've debated 'Split String To Characters' and then iterating through the list and concatenating each letter individually to a ${endString} var (skipping first entry of the list ofc), but that's clumsy and I'm hoping there's a cleaner/simpler solution out there than this...
#{cutFirstLetter}= Split String To Characters ${TABLE}[0]
${lenOfListStringOfChar}= Get Length ${cutFirstLetter}
${endString}= ${EMPTY}
:FOR ${i} IN RANGE 1 ${lenOfListStringOfChar}
\ ${temp}= ${cutFirstLetter}[${i}]
\ ${endString}= Catenate ${endString} ${temp}
Assume ${TABLE} is just a list of strings. The output of that above code works, but it's clunky. I am trying to compare it to a list of the list of valid positions, so I get (not running that above code)
Ex: 'DeveloperContributor != CDeveloperContributor'
Get Substring from the String library:
${endString}= Get Substring ${TABLE}[0] 1
Alternatively, plain old python string slice, through Evaluate:
${endString}= Evaluate """${TABLE}[0]"""[1:]

How can I use a specified order of strings to index from a cell array?

I am trying to index from a cell aray of a number of potential reference files to use for a comparison. The comparison files have distinct parts of their file names that I'd like to use to specify a single reference file.
However, I'm only able to return reference files that contain the three distinct parts, in any order. How can I enforce the order?
Example:
The comparison file is:
deg_baseFileName = "Test1_female_44k_70dBA_babble7ch_1sp_20k_00dBA_48k"
I use strsplit to break the filename into parts:
deg_parts = strsplit(deg_baseFileName, "_");
The distinguishing parts are:
deg_parts(2), deg_parts(4), deg_parts(8)
In this case: "female", "70dBA", "00dBA" - in that order.
I use these functions to identify and index with the distinguishing parts:
strToFind = {string(deg_parts(2)),string(deg_parts(4)),string(deg_parts(8))}'; % Strings to match
fun = #(s)~cellfun('isempty',strfind(ref_files,s));
out = cellfun(fun,strToFind,'UniformOutput',false);
idx = all(horzcat(out{:}),2);
However, the index returns two values from my reference file cell array:
Ref_female_44k_00dBA_babble7ch_1sp_20k_70dBA_48k.wav
Ref_female_44k_70dBA_babble7ch_1sp_20k_00dBA_48k.wav
Both contain the distinguishing parts, but only the second in the correct order.
Is there a way I can enforce the order in my out call?
Thanks!
In the simplest case, where the comparison and reference files only differ in their first part, you can use strrep:
refFile = strrep(deg_baseFileName, 'Test1', 'Ref');
If you know what the other parts of the file name will be, and they are the same for all the reference files but differ from the comparison file, you can just use sprintf to create your file name:
refFile = sprintf('Ref_%s_44k_%s_babble7ch_1sp_20k_%s_48k.wav', ...
deg_parts(2), deg_parts(4), deg_parts(8));
If you don't know or care what the other parts could be, you can generalize the above to create a match expression for use with regexp to find the index of reference files with the correct order:
expr = sprintf('Ref_%s_[^_]+_%s_[^_]+_[^_]+_[^_]+_%s_[^_]+.wav', ...
deg_parts(2), deg_parts(4), deg_parts(8));
index = ~cellfun('isempty', regexp(ref_files, expr));

Resources