python代碼實例大小寫轉換,首字母大寫,去除特殊字符
總結我們在平常開發過程中對字符串的一些操作:
#字母大小寫轉換
#首字母轉大寫
#去除字符串中特殊字符(如:'_','.',',',';'),然后再把去除后的字符串連接起來
#去除'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'中的'_',并且把從第一個'_'以后的單詞首字母大寫
def get_str(oriStr,splitStr):
str_list = oriStr.split(splitStr)
if len(str_list) > 1:
for index in 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 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
>>>
本文由用戶 gcmc 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!