Home > Net >  How to convert to uppercase the second and penultimate letter of a string list in Python using a lam
How to convert to uppercase the second and penultimate letter of a string list in Python using a lam

Time:03-08

I have this code but it is returning the first letter. I need the second and penultimate letter to be uppercase

def first_last_uppercase(array):
  serie = pd.Series(array)
  return serie.map(lambda x: x[0].upper()   x[1:-1]   x[-1].upper())

first_last_uppercase(languages)

Actual result:

0        PythoN
1           PhP
2          JavA
3    JavascripT
4           C  
5           SqL

Expected result:

0        pYthOn
1           pHp
2          jAVa
3    jAvascriPt
4           c  
5           sQl

any idea

CodePudding user response:

Remember Python is 0-indexed, so the 2nd element is 1. The last element of an iterable is -1, so the second-to-last is -2. So, modify your return statement to say

return serie.map(lambda x: x[0]   x[1].upper()   x[2:-2]   x[-2].upper()   x[-1])

It's a little bulky, but I think it works for your input:

>>> x = ["python", "php", "java", "javascript", "c  ", "sql"]
>>> serie = pd.Series(x)
>>> serie.map(lambda x: x[0]   x[1].upper()   x[2:-2]   x[-2].upper()   x[-1])
0        pYthOn
1          pHHp
2          jAVa
3    jAvascriPt
4          c   
5          sQQl

Wait, it returned pHHp, c , and sQQl for "php", "c ", and "sql", respectively. If I try a 2-character string, like "c#", I get "c#C#". And if I try giving it just a single letter, like "c", it dies with an IndexError.

You need to check the length of the string before you pass it to the lambda, which would be completely unreadable if you tried to put it all in a single lambda. Instead, define a function and use that.

def two_caps(thing: str) -> str:
    if len(thing) > 3:
        new_thing = thing[0]   thing[1].upper()   thing[2:-2]   thing[-2].upper()   thing[-1]
    elif len(thing) == 3:
        new_thing = thing[0]   thing[1].upper()   thing[2]
    else:
        new_thing = thing
    return new_thing

This returns properly-capitalized strings for inputs >= 3. If the len() is < 3, it returns the original thing. Now you can use this return statement:

return serie.Map(lambda x: two_caps(x))

and you should be good to go.

CodePudding user response:

Use capitalize and slice the middle part with 1:-2 to get an empty string when the input is short.

def first_last_uppercase(array):
  serie = pd.Series(array)
  return serie.map(lambda x: x[0].lower()   x[1:-2].capitalize()   x[-2:].capitalize())

a = ["python", "php", "java", "javascript", "c  ", "sql"]
first_last_uppercase(a)

Output:

0        pYthOn
1           pHp
2          jAVa
3    jAvascriPt
4           c  
5           sQl
dtype: object
  • Related