current position:Home>Python code reading (Chapter 69): case conversion of initial letters

Python code reading (Chapter 69): case conversion of initial letters

2022-02-02 03:59:50 FelixZ

Python Code reading collection Introduction : Why not recommend Python Beginners directly look at the project source code

The code read in this article realizes the conversion of the first letter of the string into uppercase , Or lowercase function .

The code snippet read in this article comes from 30-seconds-of-python.

capitalize

def capitalize(s, lower_rest = False):
  return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])])

# EXAMPLES
capitalize('fooBar') # 'FooBar'
capitalize('fooBar', True) # 'Foobar'
 Copy code 

capitalize The function receives a string and an indication , Returns the initial converted String .

The function uses list slicing s[:1] Get the first letter of the string , Use upper() The function converts it to uppercase . And then according to lower_rest value , Determine whether the remaining characters need to be converted to lowercase . And then use ''.join(iterable) In the form of '' An empty string is a delimited element , take iterable Concatenate strings in .

When lower_rest Is the default value False when , The remaining characters remain unchanged ; When lower_rest Pass in True when , The remaining characters are converted to lowercase .

decapitalize

def decapitalize(s, upper_rest = False):
  return ''.join([s[:1].lower(), (s[1:].upper() if upper_rest else s[1:])])

# EXAMPLES
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar', True) # 'fOOBAR'
 Copy code 

decapitalize Functions and capitalize The function is the opposite , In the same way . Use s[:1].lower() Convert the initial letter to lowercase . When upper_rest Is the default value False when , The remaining characters remain unchanged ; When upper_rest Pass in True when , The remaining characters are converted to uppercase .

copyright notice
author[FelixZ],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020359494775.html

Random recommended