当前位置: 首页 > 图灵资讯 > 行业资讯> 一文搞定Python大小写转换,首字母大写,去除特殊字符

一文搞定Python大小写转换,首字母大写,去除特殊字符

发布时间:2025-09-22 10:56:12

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

#转换字母大小写

#首字母转大写

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

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

代码实例:

#转换字母大小写
#首字母转大写
#去除字符串中的特殊字符,如'_','.',',',';'),然后将去除的字符串连接起来
#去除'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'中的'_',并且从第一'开始;_'以后的单词首字母大写
defget_str(oriStr,splitStr):
str_list=oriStr.split(splitStr)
iflen(str_list)>1:
forindexinrange(1,len(str_list)):
ifstr_list[index]!='':
str_list[index]=str_list[index][0].upper()+str_list[index][1:]
else:
continue
return''.join(str_list)
else:
returnoriStr

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

相关文章

Python中reduce函数和lambda表达式的学习

Python中reduce函数和lambda表达式的学习

2025-09-25
Python小白必学的面向对象

Python小白必学的面向对象

2025-09-25
一个例子解释python装饰器

一个例子解释python装饰器

2025-09-25
深入理解Python的set和dict

深入理解Python的set和dict

2025-09-25
Python中正则表达式的巧妙使用

Python中正则表达式的巧妙使用

2025-09-25
5分钟搞定Python中函数的参数

5分钟搞定Python中函数的参数

2025-09-25