Search code examples
pythonlowercase

lowercase first n characters


I'm trying to lowercase the first n characters in a string.

For example, say I want to lowercase the first 4 characters in this string:

String1 = 'HELPISNEEDED'

I would like the output to look like this:

String1 = 'helpISNEEDED'

I thought I could use this:

String1 = String1[4].lower() + String1[5:]

but this gives me this output:

String1 = 'iSNEEDED'

Any idea on how I'm doing this wrong?


Solution

  • You selected just one character. Use a slice for both parts:

    String1 = String1[:4].lower() + String1[4:]
    

    Note that the second object starts slicing at 4, not 5; you want to skip 'HELP', not 'HELPI':

    >>> String1 = 'HELPISNEEDED'
    >>> String1[:4].lower() + String1[4:]
    'helpISNEEDED'
    

    Remember: the start index is inclusive, the end index is exclusive; :4 selects indices 0, 1, 2, and 3, while 4: selects indices 4 and onwards.