当前位置:Gxlcms > Python > python开发

python开发

时间:2021-07-01 10:21:17 帮助过:64人阅读

总结我们在平常开发过程中对字符串的一些操作:

#字母大小写转换

#首字母转大写

#去除字符串中特殊字符(如:'_','.',',',';'),然后再把去除后的字符串连接起来

#去除'hello_for_our_world'中的'_',并且把从第一个'_'以后的单词首字母大写

代码实例:

  1. #字母大小写转换
  2. #首字母转大写
  3. #去除字符串中特殊字符(如:'_','.',',',';'),然后再把去除后的字符串连接起来
  4. #去除'hello_for_our_world'中的'_',并且把从第一个'_'以后的单词首字母大写
  5. low_strs = 'abcd'
  6. uper_strs = 'DEFG'
  7. test_strA = 'hello_world'
  8. test_strB = 'goodBoy'
  9. test_strC = 'hello_for_our_world'
  10. test_strD = 'hello__our_world_'
  11. #小写转大写
  12. low_strs = low_strs.upper()
  13. print('abcd小写转大写:', low_strs)
  14. #大写转小写
  15. uper_strs = uper_strs.lower()
  16. print('DEFG大写转小写:', uper_strs)
  17. #只大写第一个字母
  18. test_strB = test_strB[0].upper() + test_strB[1:]
  19. print('goodBoy只大写第一个字母:', test_strB)
  20. #去掉中间的'_',其他符号都是可以的,如:'.',',',';'
  21. test_strA = ''.join(test_strA.split('_'))
  22. print('hello_world去掉中间的\'_\':', test_strA)
  23. #去除'hello_for_our_world'中的'_',并且把从第一个'_'以后的单词首字母大写
  24. def get_str(oriStr,splitStr):
  25. str_list = oriStr.split(splitStr)
  26. if len(str_list) > 1:
  27. for index in range(1, len(str_list)):
  28. if str_list[index] != '':
  29. str_list[index] = str_list[index][0].upper() + str_list[index][1:]
  30. else:
  31. continue
  32. return ''.join(str_list)
  33. else:
  34. return oriStr
  35. print('去除\'hello_for_our_world\'中的\'_\',并且把从第一个\'_\'以后的单词首字母大写:', get_str(test_strC,'_'))
  36. print('去除\'hello__our_world_\'中的\'_\',并且把从第一个\'_\'以后的单词首字母大写:', get_str(test_strD,'_'))

运行效果:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================================ RESTART ================================

>>>

abcd小写转大写: ABCD

DEFG大写转小写: defg

goodBoy只大写第一个字母: GoodBoy

hello_world去掉中间的'_': helloworld

去除'hello_for_our_world'中的'_',并且把从第一个'_'以后的单词首字母大写: helloForOurWorld

去除'hello__our_world_'中的'_',并且把从第一个'_'以后的单词首字母大写: helloOurWorld

>>>

人气教程排行