Hyun J
Hyun J

Reputation: 11

How do i reference a character in a string within a list with python

I seem to have trouble with this code, keeps on telling me how my list indices must be integers or slices, not strings. Its a program that essentially makes a phrase into an capitalized acroynm IE. universal serial bus = USB

def initials(phrase):
    words = phrase.split()
    result = ""
    for word in words:
        result += words[word][0]
    return result.upper()

print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS

How do I correctly reference the character in the string.

Upvotes: 0

Views: 936

Answers (3)

Vera
Vera

Reputation: 41

The Fix

You're just one line off. It should be:

def initials(phrase):
    words = phrase.split()
    result = ""
    for word in words:
        result += word[0] # correction is here
    return result.upper()
print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS

Explanation

word is an individual word from your string of words (i.e. "Universal" from "Universal Serial Bus"). The first index ([0]) is the first letter that you're looking for (i.e. "U" out of "Universal").

words[word][0] translates to something like "Universal Serial Bus"[Universal][0], which is why you're getting the error (what is the "Universal" index of something haha). word[0] on the other hand translates to something like "Universal"[0].

Additional Explanation

The functionality like I think what you're expecting would be:

def initials(phrase):
    words = phrase.split()
    result = ""
    for word in range(len(words)):
        result += words[word][0]
    return result.upper()

In your example and my initial solution word is a string pulled from the list of words (i.e. 'Universal' from ['Universal', 'Serial', 'Bus']). From how you wrote your code I think you may be expecting word to work more like an index (i.e. words is a list of indices [0, 1, 2] that the for loop iterates through, and word would be the index of each individual word. Both solutions work and are valid but the first is arguably more "pythonic."

Upvotes: 2

The Fool
The Fool

Reputation: 20467

The problem is that the for loop doesn't yield the index, but the value.

for word in words:
    # word is not the index
    # its not an integer

You can use enumerate to get the index.

for index, word in enumerate(words):
    # index is an iteger
    # word is the value

However, since you have the word already at hand. You may not even need to use the index at all.

result += word[0]

Upvotes: 2

Melgov
Melgov

Reputation: 1

Try this, it could help:

def fn_get_initials(ar_string):
    result="".join([i[0] for i in ar_string.split()])
    return str(result).upper()

fn_get_initials("Universal Serial Bus")

Upvotes: 0

Related Questions