• 技术文章 >常见问题 >Python常见问题

    python字符串大小写转换的方法是什么

    silencementsilencement2019-10-10 13:09:16原创2655

    字符串可能是我们实际开发中用的最多的数据类型了,关于字符串有很多的使用方法,如大小写转换,分割,增加,替换等。下面说一下常用的字符串大小写转换的方法。

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

    1

    2

    3

    4

    #字母大小写转换

    #首字母转大写

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

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

    代码实例:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    #字母大小写转换

    #首字母转大写

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

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

    low_strs= 'abcd'

    uper_strs= 'DEFG'

    test_strA= 'hello_world'

    test_strB= 'goodBoy'

    test_strC= 'hello_for_our_world'

    test_strD= 'hello__our_world_'

       

    #小写转大写

    low_strs= low_strs.upper()

    print('abcd小写转大写:', low_strs)

       

    #大写转小写

    uper_strs= uper_strs.lower()

    print('DEFG大写转小写:', uper_strs)

       

    #只大写第一个字母

    test_strB= test_strB[0].upper()+ test_strB[1:]

    print('goodBoy只大写第一个字母:', test_strB)

       

    #去掉中间的'_',其他符号都是可以的,如:'.',',',';'

    test_strA= ''.join(test_strA.split('_'))

    print('hello_world去掉中间的\'_\':', test_strA)

       

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

    def get_str(oriStr,splitStr):

        str_list= oriStr.split(splitStr)

        if len(str_list) >1:

            for indexin range(1,len(str_list)):

                if str_list[index] != '':

                    str_list[index]= str_list[index][0].upper()+ str_list[index][1:]

                else:

                    continue

            return ''.join(str_list)

        else:

            return oriStr

       

    print('去除\'hello_for_our_world\'中的\'_\',并且把从第一个\'_\'以后的单词首字母大写:', get_str(test_strC,'_'))

    print('去除\'hello__our_world_\'中的\'_\',并且把从第一个\'_\'以后的单词首字母大写:', get_str(test_strD,'_'))

    更多学习内容,请点击python学习网

    专题推荐:类型转换
    上一篇:怎么安装python才能不失败? 下一篇:python语言中的错误有哪些

    相关文章推荐

    • Python中怎么转换字符串大小写• Python字符串大小写转换的函数及用法• 初学者必看的python中类型转换• python变量名不区分大小写吗• python是如何进行类型转换的

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网