当前位置:  首页>> 技术小册>> Python合辑4-130个字符串操作示例

将 Camel Case 转换为 Snake Case 并更改给定字符串中特定字符的大小写

  1. import re
  2. def convert(oldstring):
  3. s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', oldstring)
  4. return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
  5. # Camel Case to Snake Case
  6. print(convert('CamelCase'))
  7. print(convert('CamelCamelCase'))
  8. print(convert('getHTTPResponseCode'))
  9. print(convert('get2HTTPResponseCode'))
  10. # Change Case of a particular character
  11. text = "python programming"
  12. result = text[:1].upper() + text[1:7].lower() \
  13. + text[7:8].upper() + text[8:].lower()
  14. print(result)
  15. text = "Kilometer"
  16. print(text.lower())
  17. old_string = "hello python"
  18. new_string = old_string.capitalize()
  19. print(new_string)
  20. old_string = "Hello Python"
  21. new_string = old_string.swapcase()
  22. print(new_string)

Output:

  1. camel_case
  2. camel_camel_case
  3. get_http_response_code
  4. get2_http_response_code
  5. Python Programming
  6. kilometer
  7. Hello python
  8. hELLO pYTHON

该分类下的相关小册推荐: