w3resource

Python: Decapitalize the first letter of a given string

Python String: Exercise-98 with Solution

Write a Python program to decapitalize the first letter of a given string.

  • Use list slicing and str.lower() to decapitalize the first letter of the string.
  • Use str.join() to combine the lowercase first letter with the rest of the characters.
  • Omit the upper_rest parameter to keep the rest of the string intact, or set it to True to convert to uppercase.

Sample Solution:

Python Code:

# Define a function to decapitalize the first letter of a string
# Optionally, capitalize the rest of the string if 'upper_rest' is True (default is False)
def decapitalize_first_letter(s, upper_rest=False):
    # Join the first letter in lowercase with the rest of the string, optionally capitalizing the rest
    return ''.join([s[:1].lower(), (s[1:].upper() if upper_rest else s[1:])])
	
# Test the function with different input strings and print the results
print(decapitalize_first_letter('Java Script'))
print(decapitalize_first_letter('Python')) 

Sample Output:

java Script
python

Flowchart:

Flowchart: Decapitalize the first letter of a given string.

Python Code Editor:

Previous: Write a Python program to convert a given string to snake case.
Next: Write a Python program to split a given multiline string into a list of lines.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.