def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
initials = ""
for name in name_list: # go through each name
initials += name[0].upper() # append the initial
## ^^ what is happening here?
return initials
What is the += in this context? Is it incrementing the value in the list?
The line initials += name[0].upper() # append the initial adds the first character to a string, the process:
Split a string into a list (So john doe becomes ['john', 'doe'])
Iterate over each item in that list
For each item in that list, append to the empty string the first character, capitialized
For example, for john, get the first character j and capitalize it as J
Return the initials (JD in this case)
Related
I want to capitalize a char in a string, specifically using a for loop. Can someone show how this is done using the code below. or something simpler but still using for loop iterations
name = input("Enter name")
name_list = list(name)
for i in range(len(name_list)):
if i == name_list[3]:
name_list = name_list[3].upper
else:
name_list += i
print(name_list)
Assuming this is Python, you can it by assigning the newly uppercase letter to the list at the lowercase letter's index. For example, if we want to make every third letter upper case in the string enter name, then:
name = "enter name"
name_list = list(name)
for i in range(len(name_list)):
if i % 3 == 0:
name_list[i] = name_list[i].upper()
print(''.join(name_list))
Output:
EntEr NamE
I'm fairly new to python, so I'm trying to take a string with two words that could be a mix of upper and lower case separated by 1 or more spaces (like in my example with the variable name) and turn it into a string like
"Banana Split", where the first letter of each word is in caps and the rest are lower, spaces removed except for one in between the two words. Here's what I got:
name = "banAna sPlit"
name = name.lower()
name = name.split()
for i in name:
i = i[0].upper() + i[1:]
name = " ".join(i)
print(name)
Why does this only split the first word? Doesn't the for loop address each element of the list, which contains "banana" and "split"? How should I fix this?
Try using title() function!
name = "banAna sPlit"
name = name.lower()
name = name.split()
array = []
for i in name:
array.append(i.title())
name = " ".join(array)
print(name)
This also removes the whitespace between words!
You can create a new list with the adjustments you are looking for.
name = "banAna sPlit"
name = name.lower()
name = name.split()
name = [i[0].upper() + i[1:] for i in name]
name = " ".join(name)
print(name)
i takes on the value of the element, but assigning to i will reassign the variable, and not assign to the value of the list. Instead, enumerate the list so you get an index and a value, then assign the new value to the list with the index:
for i, v in enumerate(name):
name[i] = v[0].upper() + v[1:]
name = " ".join(name)
Assigning to i doesn't assign to the list element, it just assigns to the variable.
Use a list comprehension to create a new list with the modifications.
name = [i[0].upper() + i[1:] for i in name]
name = " ".join(name)
This takes into account more than two spaces
name = "banAna sPlit"
names = name.split(' ')
names = str([" ".join(filter(None,names))]).title()
print(names)
>>> ['Banana Split']
This is my code. I'm trying to take an input from the user, put it in a list, then check every elements if it is less than 5 characters.
It's supposed to print all the names under such condition but it only returns the last element that fits the condition.
My code:
#function to check the length of the characters
def test(names):
for x in names:
if len(x) <= 5:
print(x)
return x
#ask input from the user
names = input("Enter names: ").split()
#convert to a list
lst = list(names)
#container
viewList = test(names)
#print names under 5 characters
print("Names under five characters: ", viewList)
#just to test the elements in the list
print(names)
The Output:
Enter names: kent monique jeff ban
kent
jeff
ban
Names under five characters: ban
['kent', 'monique', 'jeff', 'ban']
As you can see, it only prints the last element. What mistake am I doing here?
Use this
#function to check the length of the characters
def test(names):
a = []
for x in names:
if len(x) <= 5:
print(x)
a.append(x)
return a
#ask input from the user
names`enter code here` = input("Enter names: ").split()
#convert to a list
lst = list(names)
#container
viewList = test(names)
#print names under 5 characters
print("Names under five characters: ", viewList)
#just to test the elements in the list
print(names)
Using a generator instead you could use:
# function to check the length of the characters
def test(names):
for x in names:
if len(x) <= 5:
yield x
# ask input from the user
names = input("Enter names: ").split()
# container
viewList = [name for name in test(names)]
# print names under 5 characters
print("Names under five characters: ", viewList)
# just to test the elements in the list
print(names)
Note that after using split() your result is already a list, so converting it to a list is redundant.
An often used method is filter(...) as in
viewList = list(filter(lambda x: len(x) <= 5, names))
I am trying to create a function that takes a string as an argument and returns a list of all of the generated words by swapping a letter with its immediate neighbor.
I first take each letter and create a list of strings and each string contains one letter.
Then I iterate through the new list of letters and try to swap them.
Then I join the letters together to form a string.
Then I append the new string to the list that I return.
Here is my code. Please tell me how to fix it. I don't want it to display the passed word in the list. Thank you.
def mixedString(word):
word = word.lower()
letters = []
newArray = []
for n in word:
letter = f"{n}"
letters.append(letter)
newList = []
for i in range(len(letters)):
newWord = ""
newArray = letters[i:] + letters[:i]
newWord = "".join(newArray)
newList.append(newWord)
return newList
myWord = "Dog"
print(mixedString(myWord))
Hint: there are only n - 1 distinct words where one letter of the original word has been swapped. To see why, note that ab only has ba as result.
If a word has the letters are position i and i+1 swapped the letters before i are unchanged and the letters after i + 1 also are unchanged.
def swap(s, i):
return s[:i] + s[i+1] + s[i] + s[i+2:]
def neighbors(s):
return [swap(s, i) for i in range(len(s)-1)]
You can swap letters like this:
def swap(string, place_1, place_2):
string = list(string)
string[place_1], string[place_2] = string[place_2], string[place_1]
return ''.join(string)
a = '1234'
print(swap(a, 1, 2))
>>> 1324
There are many points of improvement, but I will be addressing the one you ask for
I don't want it to display the passed word in the list.
Just skip the first iteration in the relevant loop, e.g. by replacing this:
for i in range(len(letters)):
with this:
for i in range(1, len(letters)):
I created a Python function that takes an argument, fullname, gets fullname's initials and prints them out capitalized. But there's a problem with my code - it only works with two names. It breaks if the fullname has a middle name, i.e. Daniel Day Lewis.
Here is what I tried:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
return(first.upper() + second.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
Obviously this attempt only includes two variables, one for the first name and one for the second name. If I add a third variable, like this:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
third = name_list[2][0]
return(first.upper() + second.upper() + third.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
I get:
IndexError: list index out of range on line 10
(which is the line)
third = name_list[2][0]
Of course this function does work if I change fullname to "Ozzie Smith Jr". But my function has to work regardless of whether there are 1, 2, 3, or 4 names in fullname. I need to say something like:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
#if fullname has a second name:
second = name_list[1][0]
#if fullname has a third name:
third = name_list[2][0]
#if fullname has one name:
return(first.upper())
#if fullname has two names:
return(first.upper() + second.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper + fourth.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
How do I say "if fullname has a second name or third name or fourth name, return the uppercase initial" in Python? Or am I on the right track? Thank you.
You can make use of a list comprehension:
s = ''.join([x[0].upper() for x in fullname.split(' ')])
edit: should probably explain a little more
list comprehensions allow you to build a list as you iterate.
So first we build a list by splitting fullname with a space fullname.split(' '). As we get those values, we take the fist letter x[0] and uppercase it .upper(). Finally we join the list into one with no spaces ''.join(...).
This is a nice one liner that's really fast and will pop up in various forms as you continue working with python.
How about something like:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
initials = ""
for name in name_list: # go through each name
initials += name[0].upper() # append the initial
return initials
This is my answer:
Splitting the string into a list
Iterate through elements using range and i
Taking index 0 for each element during iteration (Hence words[i][0])
words[i][0].upper for the upper case requirement for the question
def initials(phrase):
words = phrase.split()
result = ""
for i in range(len(words)):
result += words[i][0].upper()
return result
print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
This should work
map(str.upper, zip(*the_persons_name.split())[0])
the other variance of one liner as below, we can join all the initials 1st then do the upper 1 shot at last
''.join(i[0] for i in a.split()).upper()
def initials(name):
words = name.split()
result = ""
for word in words:
result += word[0].upper()
return result