How to abbreviate a two word name in python? - python

I am trying to abbreviate a first name and a last name. For example, if I enter Diesan Romero (that's my name), I need to return the initials D.R with that intermediate point.
I had no idea where to start. So I went to the Python documentation and tried to convert the text string to a list, iterate the list, and then choose those characters that were uppercase. This is the code that I have achieved so far.
def convertToList(name):
lista = []
for i in name:
if i.isupper():
lista.append(i)
return lista
if __name__ == "__main__":
print(convertToList("Diesan Romero"))
In that code I try to create the list, but it only returns me one value.

def convertToList(name):
final_name = []
name_list = name.split()
for i in name_list:
final_name.append(i[0])
print '.'.join(final_name)
convertToList('Diesan Romero')

If your names will always be in the format - “first last”, you may be able to do the following:
def get_initials(name):
names = name.split(' ')
return ' '.join([f"{n[0]}." for n in names])
print(get_initials('John Doe'))

Looks like you are returning lista as soon as you first find an upper-case letter. Try de-indenting the "return" by two tabs to shift it after the end of the for loop.

Related

to print name with a pattern in python

I ask the user to enter it's name and I print the pattern
eg:
W
WO
WOR
WORL
WORLD
s=input("Enter your name")
l=s.split()
i=len(l)
for m in range(0,i):
for s in range(0,m):
print(s)
print()
I have written this program where am I wrong please help. A beginner here
Others have given you code that does what you want it to do; I'll try to explain why your code doesn't do what you think it would do.
#s=input("Enter your name")
# Let's pretend that the given word from the user was 'WORLD' as in your example.
s = "WORLD"
l=s.split()
The above line s.split() uses the default-behaviour of the built-in str.split() method. Which does the following if we look at the help-file:
split(self, /, sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string.
sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
That means that it will try to split your given string on each whitespace-character inside of it and return a list containing the results. "WORLD".split() would therefore return: ['WORLD']
i=len(l)
This returns 1, because the result of s.split().
Now let's break down what happens inside of the for-loop.
# This is essentially: for m in range(0, 1) which will only loop once, because range is non-inclusive
for m in range(0,i):
# This is range-command will not execute, because the first value of m will be 0
# Because range is non-inclusive, running range(0, 0) will not return a value.
# That means that nothing inside of the for-loop will execute.
for s in range(0,m):
print(s)
print()
All of this results in only the print() statement inside of the first for-loop being executed, and it will only be executed once because of how the range-function works with the values it has been given.
We can do this without using 2 loops.
s = input("Enter your name")
for i in range(len(s)+1):
print(s[:i])
#Output:
W
WO
WOR
WORL
WORLD
Don't complicate the code unnecessarily.
A string you can think of as a list of characters on which to iterate, without resorting to splitting.
If you use Python's List Slicing, you can point to the positions of the characters you are interested in printing.
Your code becomes:
name = input("Enter your name: ")
for i in range(len(name)):
print(name[:i+1])

Finding the values corresponding with user input from a list of tuples

As a foreword, I'm quite new to python, and coding in general.
I'm trying to get the following code to find the specific values in the foodgroups tuple that match with user input (ie: Dairy, Nuts, and Grain) and attach them to Output (ie: Dairy and Nuts). The line with Output was gotten from another website when I was first making this. The code works when the user provides an input that only contains one item without any symbols or spaces (ie: Dairy) but anything extra causes Output to be blank when printed.
userinput = input("Enter foodgroups ate in the last 24hrs : ").title()
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
Output = list(filter(lambda x:userinput in x, foodgroups))
if foodgroups[0] or foodgroups[1] or foodgroups[2] or foodgroups[3] in userinput:
print(Output,"is present in your list, " + userinput)
else:
print("Negative.")
I've thought of swapping around foodgroups and userinput, but that results in a TypeError, and turning the tuple into a string has Output always return blank.
I've asked others how to fix this, but they've had no better luck. Any help is appreciated!
If userinput is a comma separated string then split it and use a list:
userinput = input("Enter foodgroups ate in the last 24hrs : ")
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
uin = userinput.split(",")
grp = []
for x in uin:
if x in foodgroups:
grp.append(x)
grp is the user defined foods in foodsgroup
The main thing is that you want to use split to separate individual words from the user input into a list of words. I also swapped x and seafoods in your lambda.
If the user separates each word by one or more spaces, here's how to change your code to work:
userinput = input("Enter foodgroups ate in the last 24hrs : ").title()
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
userfoods = userinput.split()
Output = list(filter(lambda x: x in userfoods, foodgroups))
print(Output,"is present in your list, " + str(userinput))
As other's mention, you need to use split() to separate individual items in the input:
userfoods = userinput.split()
But even after that your if condition isn't correct:
if foodgroups[0] or foodgroups[1] or foodgroups[2] or foodgroups[3] in userinput:
The thing to realize here is that or and in are operators that only work with the immediately adjacent 2 values. We can add parentheses to see how this works:
if (((foodgroups[0] or foodgroups[1]) or foodgroups[2]) or (foodgroups[3] in userinput)):
This means that foodgroups[0] or foodgroups[1] evaluates to just the value of foodgroups[0], so foodgroups[1] is basically ignored. This isn't what you want. Instead, you need to check in for each item:
if foodgroups[0] in userinput or foodgroups[1] in userinput or foodgroups[2] in userinput or foodgroups[3] in userinput:
But as you can see this gets very lengthy. So using a loop or list comprehension or generator expression can reduce the amount of code you need to write as others have already shown.

Pythonic way to match a string if contained in a set of strings

I am trying to match names by using the first, second, and last names, either in the correct order or not, using all of them or not. So far I've got this code and it sort of works, but I think it's not the right way of doing it. Do you know another way of doing this?
The names in the data set look like this:
name = 'DAVID SCOTT MUSTAIN'
What I want is to match that name if I search for 'DAVID', 'MUSTAIN SCOTT', 'SCOTT DAVID', etc..
The function I got so far looks like this:
def search_name(somename):
for full_name in some_dataset:
if set(somename.upper().split()).issubset(full_name.split()):
print('match:', full_name)
If I input something like 'DAV' or 'SCOT', this will not match anything. How should I proceed in order to make a match even with incomplete names? If I split
the names into single letters it will match every name with those letters without checking the order of the letters.
You can use any to check if any name in somename is a subset of any of the names in full_name
def search_name(somename):
for full_name in some_dataset:
if any(n.upper() in fn for n in somename.split() for fn in full_name.split()):
print('match:', full_name)
And here is an example using sum and a dictionary to pick the name with the most matches:
def search_name(somename):
matches = {}
for full_name in some_dataset:
matches[full_name] = sum(1 for n in somename.split() for fn in full_name.split() if n.upper() in fn)
best_matches = [k for k,v in matches.items() if v == max(matches.values()) if v != 0]
for match in best_matches:
print('match:', match)
I'm sure there are better ways to write this function but i'm very sleep deprived..
As for your second question perhaps you could print/return all the items in the best_matches list?
I made a little function that use more statements
def search_name(name, toSearch, num = 2):
found = []
for word in name.split():
search = word[:num]
for letter in word[num:]:
search += letter
isThere = [data for data in toSearch.split() if data in search]
if isThere:
found += isThere
break
return len(toSearch.split()) == len(found)
name = 'DAVID SCOTT MUSTAIN'
if search_name(name,'TA'):
print(name)
else:
print('Nothing')
You want this ?
I might use
if full_name in somename and not set(full_name.split()) - set(someone.split())
to see if its a substring and it contains no extra short names.

Remove letters from a given string

So my homework assignment is to remove initials of a given name, from a given string, using user inputs to define the variables. As I run the script below, it only registers one name.
def removeChar(initials, string):
initials = initials
string = string
for char in initials:
modified = string.replace(char, "")
print modified
return modified
def getInitials(name, string):
initials = ""
for i in name.lower().split():
initials += i[0]
print initials
removeChar(initials, string)
def main():
name = raw_input("What is your name? \n")
string = raw_input("What string would you like to remove your initials from? \n")
getInitials(name, string)
This is the output:
What is your name?
John Doe
What string would you like to remove your initials from?
Arjajbian Ndigdhts
Arjajbian Nights
Why wouldn't it remove the first initial?
Your problem lies here:
modified = string.replace(char, "")
You are always using replace on the original string, so it removes each individual character from the original string and returns a new one. Just use string = string.replace(char, "")
Or else your function will always return a string that is the original string with the last initial removed.
you dont need the
initials = initials
string = string
as this does nothing your telling to make this variable the same as it is already
Also
I think it is this
modified = string.replace(char, "")
you make this create a variable called modified but later on in the code you are saying to get String and not modified
either change String to modified apart from in the top def or change the modified to string and then it will work hopefully
While #juanpa.arrivillaga has pointed out your problem, there is a much more Pythonic way to remove the characters j and d from your input string; Using a generator expression:
>>> input_str = "Arjajbian Ndigdhts"
>>> ''.join(c for c in input_str if c.lower() not in 'jd')
'Arabian Nights'
>>>
This works by iterating through input_str and only passing the characters to ''.join() which are not j or d.

Make an input string into a list in python

I want to turn the string:
avengers,ironman,spiderman,hulk
into the list:
['avengers','ironman','spiderman','hulk']
I tried
list = raw_input("Enter string:")
list = list.split()
but it's not working the right way as I need it, it's taking the whole string and makes it as one item in the list (it works fine without the "," but that's not what I need)
If you dont pass anything to split method, it splits on empty space. Pass the comma as argument:
my_list.split(',')
edited so you dont use list as name
Hello guys i want to make for example the next string:
avengers,ironman,spiderman,hulk into the next list:
['avengers','ironman','spiderman','hulk']
i tried that `
list = raw_input("Enter string:")
list = list.split()
Do this instead:
list = raw_input("Enter string:")
list = list.split(",")
And, as mentioned by the others, you might want to not use the name "list" for your string/array.

Categories