2

I have been trying to create a small function for a menu project I have where the function takes a string as input and capitalizes the first letter of each sentence. I think I'm pretty close to having it right, but it keeps giving me a concatenation error that I can't seem to fix. Anyone know where I went wrong here?

def fix_capitalization(usrStr):
    s1 = usrStr.split(". ")
    s2 = [s1[0].capitalize() + s1[1:] for i in s1]
    st2 = '. '.join(s2)

    return st2
hygull
  • 8,464
  • 2
  • 43
  • 52
liam12808
  • 109
  • 6
  • What is the concatenation error? –  Apr 14 '19 at 22:35
  • @Tom TypeError: can only concatenate str (not "list") to str – liam12808 Apr 14 '19 at 22:38
  • Doesn't capitalize do what you want without having to use slices, anyway? https://docs.python.org/3/library/stdtypes.html#string-methods - it only does the first letter in the string. – Guy Apr 14 '19 at 22:41

2 Answers2

3

In the list comprehension you have s1[0] instead of i[0]

def fix_capitalization(usrStr):
    s1 = usrStr.split(". ")
    s2 = [i[0].capitalize() + i[1:] for i in s1]
    st2 = '. '.join(s2)

    return st2
kudeh
  • 883
  • 1
  • 5
  • 16
0

Try this:

def fix_capitalization(usrStr):

    return ".".join(list(map(lambda x: x.capitalize(),usrStr.split("."))))

This is more compact. The 2nd argument in the map()--that is usrStr.plit()-- returns a list whose items are then worked on by the lambda function. The lamda function returns a list (created by the map function). The items in this list are joined by '.'

Don Cheeto
  • 111
  • 1
  • 9