Python, how to return a triple? - python

def split_3(s):
s=s.split(".",1)
s_left=s[0]
s_right=s[1]
for words in s:
t=len(s[0])
return ("{s_left},{t},{s_right}").format(s_left=s_left,t=t,s_right=s_right)
#example: split_3('this is it.another one.')
#output='this is it,10,another one.'
#desired output= ('this is it', 10, ' another one.')
The task is to return the amount of contents in the string when the first "." appears. And then format it the way that you have the output you already see(Sentence until 1st "." , number of the contents until then, the remaining string
Like you see i already get the desired output, however i have to return it as a triple and i am not sure how to do that
I hope you can help me in this case.

you mean this?
return (s_left,t,s_right)

You can also assign to a tuple from the split, so the function becomes simpler:
def split_3(s):
s_left, s_right = s.split(".", 1)
t = len(s_left)
return (s_left, t, s_right)

Related

Remove certain characters if they are not in a specific location in a string #python

I am trying to figure out the following function situation from my python class. I've gotten the code to remove the three letters but from exactly where they don't want me to. IE removing WGU from the first line where it's supposed to stay but not from WGUJohn.
# Complete the function to remove the word WGU from the given string
# ONLY if it's not the first word and return the new string
def removeWGU(mystring):
#if mystring[0]!= ('WGU'):
#return mystring.strip('WGU')
#if mystring([0]!= 'WGU')
#return mystring.split('WGU')
# Student code goes here
# expected output: WGU Rocks
print(removeWGU('WGU Rocks'))
# expected output: Hello, John
print(removeWGU('Hello, WGUJohn'))
Check this one:
def removeWGU(mystring):
s = mystring.split()
if s[0] == "WGU":
return mystring
else:
return mystring.replace("WGU","")
print(removeWGU('WGU Rocks'))
print(removeWGU('Hello, WGUJohn'))
def removeWGU(mystring):
return mystring[0] + mystring[1:].replace("WGU","")
Other responses I seen wouldn't work on a edgy case where there is multiple "WGU" in the text and one at the beginning, such as
print(removeWGU("WGU, something else, another WGU..."))

Capitalize letter function in python

I try to write a program with a function to capitalize every first letter in expression with the addition of one dot. For example if I write hello world the result must be H.W..
My program is:
def initials(Hello World):
words = input.split(' ')
initials_words = []
for word in words:
title_case_word = word[0].upper()
initials_words_words.append(title_case_word)
output = '. '.join(initials_words)
return (initials_words)
The compilers seems that does nootexit any error but when I try to give an exression such as:print (initials(Hello World) the compiler does not give me any result.
This will do it:
def initials(input_text):
return "".join(["%s." % w.upper()[0] for w in input_text.split()])
I identified several problems:
You need to change your function signature to take a parameter called input. Because that's the variable you split. NB: input is also a built-in function so using a different variable name would be better.
Then you use initial_words_words instead of initial_words inside the loop.
You assign output but you don't use it, it should probably be outside the loop and also returned.
Not an issue but you don't need ( and ) when returning.
So a changed program would look like this:
def initials(my_input):
words = my_input.split(' ')
initials_words = []
for word in words:
title_case_word = word[0].upper()
initials_words.append(title_case_word + '.')
output = ''.join(initials_words) # or ' '.join(initials_words) if you want a seperator
return output
print(initials('Hello World')) # H.W.
I see an error when trying to run your code on the 6th line: initials_words_words.append(title_case_word).
NameError: name 'initials_words_words' is not defined
After Fixing that, the program worked fine. Try changing it to initials_words.append(title_case_word)

How do you output a list out without quotes around strings?

I'm trying to set up a block to accept only inputs that are in a list but first it asks for the inputs in the input function but I can't seem to get rid of the quotes around the strings in the list. Here is some example code:
def Sinput(acceptable):
while True:
acceptable = [str(i) for i in acceptable]
a = input('Enter'+str(acceptable[:-1]).strip('[]')+' or '+str(acceptable[-1]+': '))
if a in acceptable:
return a
break
a = Sinput([ 1, 2.01, '\'cat\'', 'dog'])
print('you entred:', a)
The input asks: Enter'1', '2.01', "'cat'" or dog: I want it to ask: Enter 1, 2.01, 'cat' or dog:
Using .replace('\'', '') won't work because the input 'cat' would no longer display correctly
Thanks for any help, I've only been doing coding for about a week.
Use .join(...) which is the recommended way for joining an iterable of strings:
a = input('Enter'+ ' ,'.join(acceptable[:-1]) + ...)
# ^^^^^^^^^
P.S. I don't see why you need a break after that return statement.
I think this would do good for you:
a = input('Enter {} or {}'.format(' ,'.join(acceptable[:-1]), acceptable[-1]))

Remove comma and change string to float

I want to find "money" in a file and change the string to float , for example, I use regular expression to find "$33,326" and would like to change to [33326.0, "$"] (i.e., remove comma, $ sign and change to float). I wrote the following function but it gives me an error
import locale,re
def currencyToFloat(x):
empty = []
reNum = re.compile(r"""(?P<prefix>\$)?(?P<number>[.,0-9]+)(?P<suffix>\s+[a-zA-Z]+)?""")
new = reNum.findall(x)
for i in new:
i[1].replace(",", "")
float(i[1])
empty.append(i[1])
empty.append(i[0])
return empty
print currencyToFloat("$33,326")
Can you help me debug my code?
money = "$33,326"
money_list = [float("".join(money[1:].split(","))), "$"]
print(money_list)
OUTPUT
[33326.0, '$']
When you do
float(i[1])
you are not modifying anything. You should store the result in some variable, like:
temp = ...
But to cast to float your number have to have a dot, not a comma, so you can do:
temp = i[1].replace(",", ".")
and then cast it to float and append to the list:
empty.append(float(temp))
Note:
Something important you should know is that when you loop through a list, like
for i in new:
i is a copy of each element, so if you modify it, no changes will be done in the list new. To modify the list you can iterate over the indices:
for i in range(len(new)):
new[i] = ...
You can use str.translate()
>>>money= "$333,26"
>>>float(money.translate(None, ",$"))
33326.0
With Python 3 you can use str.maketrans with str.translate:
money = "$33,326"
print('money: {}'.format(float(money.translate(str.maketrans('', '', ",$")))))
Output: money: 33326.0

Trouble returning variable in python function

I'm simply trying to modify a string and return the modified string, however, I'm getting "None" returned when print the variable.
def AddToListTwo(self,IndexPosition):
filename = RemoveLeadingNums(self, str(self.listbox1.get(IndexPosition))) #get the filename, remove the leading numbers if there are any
print filename #this prints None
List2Contents = self.listbox2.get(0, END)
if(filename not in List2Contents): #make sure the file isn't already in list 2
self.listbox2.insert(0, filename)
def RemoveLeadingNums(self, words):
if(isinstance(words,str)):
match = re.search(r'^[0-9]*[.]',words)
if match: #if there is a match, remove it, send it through to make sure there aren't repeating numbers
RemoveLeadingNums(self, re.sub(r'^[0-9]*[.]',"",str(words)).lstrip())
else:
print words #this prints the value correctly
return words
if(isinstance(words,list)):
print "list"
edit - multiple people have commented saying I'm not returning the value if there is match. I don't want to return it if there is. It could be repeating (ex: 1.2. itema). So, I wanted to essentially use recursion to remove it, and THEN return the value
There are multiple conditions where RemoveLeadingNums returns None. e.g. if the if match: branch is taken. Perhaps that should be:
if match:
return RemoveLeadingNums(...
You also return None if you have any datatype that isn't a string passed in.
You're not returning anything in the case of a match. It should be:
return RemoveLeadingNums( ... )

Categories