I wish to make a function which would split a name using hyphens("-")
def tag(name):
for word in list(name):
*something*
return variable
print(tag('Richard'))
desired output
'R-i-c-h-a-r-d-'
you want to use the join function on a string, which operates on the 'joiner' (in your case, '-') and accepts either a list, or another string.
So, you could have '-'.join('Richard'),
or
def tag(name):
return '-'.join(name)
Try this below :
def tag(name):
output = name[0]
for i in name[1:]:
output += '-' + i
return output
print(tag('Richard'))
OR
def tag(name):
return '-'.join("Richard")
Related
I'm trying to replace a specific substring in the keys of a dictionary with this code:
# **kwargs is taken from a function, I'm just showing the content of it
name = 'foobar'
kwargs = {'__async': 'none', 'in_width': 'foo'}
part_of_key_to_replace = {'__': '', '_': '-'}
all_attr = f"<{name} ", *(f" {key.replace((key, value) for key, value in part_of_key_to_replace.items())}='{value}'" for key, value in kwargs.items()), ">"
def join_attr(tup): # Joins the tuple to form a string
string = ''
for item in tup:
string = string + item
string = string.replace(' ', ' ')
return string
print(join_attr(all_attr))
I expected the output to be:
<foobar asnync='none' in-width='foo' >
It instead gives a SyntaxError:
File "<fstring>", line 47
SyntaxError: Generator expression must be parenthesized
I've looked up at other solutions, but they're specific to an old version of Django, which I'm not working with here.
How do I rectify this? Is there a more efficient way to do this?
I'm guessing there's an issue with the *(f"...") part.
Thanks.
I'm making a discord bot and i'm running in issue with getting list values with out extra parentheses, quotes or commas.
here's the code:
#gets slots for page
def listindexcheck(slot):
if totalitemcount > slot + (page * 9):
return slot + (page * 9)
else:
return 0
if argument == 'show':
#message set up
embed = discord.Embed(
title='title',
description='Here is your inventory',
colour=discord.Colour.red())
for i in range(9):
embed.add_field(name=f"Slot ({listindexcheck(i+1)})", value=f'Dur: {str(item_dur[listindexcheck(i+1)])}\n'
f'Mod: {str(item_mod[listindexcheck(i+1)])}\n'
f'E.lvl: {str(item_level[listindexcheck(i+1)])}\n'
f'*id:{str(item_ids[listindexcheck(i+1)])}*\n')
embed.set_footer(text='page: ' + str(page+1))
msg = await ctx.send(embed=embed)
print (type(str(item_ids[listindexcheck(i+1)])))
and here's output
Type of data before converting it to string is list
i tried to turn values to string type to get rid of at least the quotes but that didn't work
My question is is there a way to just get the values without doing anything extra to it?
Thanks
From the looks of it, item_dur[listindexcheck(i+1), item_mod[listindexcheck(i+1) item_level[listindexcheck(i+1) item_ids[listindexcheck(i+1) seem to be tuples with only one item inside. Why there is a comma inside the parenthesis ? It is because the comma makes the tuple and not the parenthesis.
Therefore, to not get parenthesis and comma when you print them, you can just get the first item of the tuple like this item_dur[listindexcheck(i+1)][0].
After you've turned it into a string you could use the replace() method to remove any extra pieces that you don't want in there. You would replace anything that you don't want in there with '' to simply remove it from the string.
Here's some info on the replace() method: https://www.w3schools.com/python/ref_string_replace.asp
You can use string.replace, and it'll be better if you make a function for this like that:
def delete_brackets(text: str):
return text.replace(')', '').replace(')', '').replace(',', '')
embed.add_field(name=f"Slot ({listindexcheck(i+1)})", value=f'Dur: {delete_brackets(str(item_dur[listindexcheck(i+1)]))}\n'
f'Mod: {delete_brackets(str(item_mod[listindexcheck(i+1)]))}\n'
f'E.lvl: {delete_brackets(str(item_level[listindexcheck(i+1)]))}\n'
f'*id:{delete_brackets(str(item_ids[listindexcheck(i+1)]))}*\n')
So this will work for you.
I have extracted text from an HTML file, and have the whole thing in a string.
I am looking for a method to loop through the string, and extract only values that are within square brackets and put strings in a list.
I have looked in to several questions, among them this one: Extract character before and after "/"
But i am having a hard time modifying it. Can someone help?
Solved!
Thank you for all your inputs, I will definitely look more into regex. I managed to do what i wanted in a pretty manual way (may not be beautiful):
#remove all html code and append to string
for i in html_file:
html_string += str(html2text.html2text(i))
#set this boolean if current character is either [ or ]
add = False
#extract only values within [ or ], based on add = T/F
for i in html_string:
if i == '[':
add = True
if i == ']':
add = False
clean_string += str(i)
if add == True:
clean_string += str(i)
#split string into list without square brackets
clean_string_list = clean_string.split('][')
The HTML file I am looking to get as pure text (dataframe later on) instead of HTML, is my personal Facebook data that i have downloaded.
Try out this regex, given a string it will place all text inside [ ] into a list.
import re
print(re.findall(r'\[(\w+)\]','spam[eggs][hello]'))
>>> ['eggs', 'hello']
Also this is a great reference for building your own regex.
https://regex101.com
EDIT: If you have nested square brackets here is a function that will handle that case.
import re
test ='spam[eg[nested]gs][hello]'
def square_bracket_text(test_text,found):
"""Find text enclosed in square brackets within a string"""
matches = re.findall(r'\[(\w+)\]',test_text)
if matches:
found.extend(matches)
for word in found:
test_text = test_text.replace('[' + word + ']','')
square_bracket_text(test_text,found)
return found
match = []
print(square_bracket_text(test,match))
>>>['nested', 'hello', 'eggs']
hope it helps!
You can also use re.finditer() for this, see below example.
Let suppose, we have word characters inside brackets so regular expression will be \[\w+\].
If you wish, check it at https://rextester.com/XEMOU85362.
import re
s = "<h1>Hello [Programmer], you are [Excellent]</h1>"
g = re.finditer("\[\w+\]", s)
l = list() # or, l = []
for m in g:
text = m.group(0)
l.append(text[1: -1])
print(l) # ['Programmer', 'Excellent']
I've comma separated values which I want to iterate and append the value dynamically like below:
def statusCode = '1001,1002,1003'
Output should look like this:
[item][code]=1001|[item][code]=1002|[item][code]=1003
If statusCode has only two value. For example:
def statusCode = '1001,1002'
Then output should be
[item][code]=1001|[item][code]=1002
I tried something like below since I'm new to groovy not sure how can achieve this with some best approach:
def statusCode= '1001,1002,1003'
String[] myData = statusCode.split(",");
def result
for (String s: myData) {
result <<= "[item][code]="+s+"|"
}
System.out.println("result :" +result);
You can use collect and join to simplify the code:
def result = statusCode.split(',').collect{"[item][code]=$it"}.join('|')
That returns [item][code]=1001|[item][code]=1002|[item][code]=1003
I am attempting to make a dictionary into a formatted string and then write it to a file, however my entire formatting seems to be incorrect. I'm not sure how to debug since all my tester cases are given different files. I was able to use the interactive mode in python to find out what my function is actually writing to the file, and man is it so wrong! Can you help me correctly format?
Given a sorted dictionary, I created it into a string. I need the function to return it like so:
Dictionary is : {'orange':[1,3],'apple':[2]}
"apple:\t2\norange:\t1,\t3\n"
format is: Every key-value pair of the dictionary
should be output as: a string that starts with key, followed by ":", a tab, then the integers from the
value list. Every integer should be followed by a "," and a tab except for the very last one, which should be followed by a newline
Here is my function that I thought would work:
def format_item(key,value):
return key+ ":\t"+",\t".join(str(x) for x in value)
def format_dict(d):
return sorted(format_item(key,value) for key, value in d.items())
def store(d,filename):
with open(filename, 'w') as f:
f.write("\n".join(format_dict(d)))
f.close()
return None
I now have too many tabs on the last line. How do I edit the last line only out of the for loop?
ex input:
d = {'orange':[1,3],'apple':[2]}
my function gives: ['apple:\t2', 'orange:\t1,\t3']
but should give: "apple:\t2\norange:\t1,\t3\n"
Adding the newline character to the end of the return statement in format_item seems to yield the correct output.
return key+ ":\t"+",\t".join(str(x) for x in value) + '\n'
In [10]: format_dict(d)
Out[10]: ['apple:\t2\n', 'orange:\t1,\t3\n']