天天看點

#Python在學習8# Python中字母大小寫轉換

Python中有些内置函數來處理字元串。

第一組函數:

Input(string):提示使用者通過鍵盤輸入字元串;

Len(string):計算字元串中的字元個數(空格是占據字元串的)

Max(string):找到字元串中ASCII碼最大的字元串

Min(string):找到字元串中ASCII碼最小的字元串

Reversed(string):字元串反轉

Sorted(string):字元串分類

關于reversed函數和sorted函數應用如下:

a_str=''.join(reversed("Woof,Woof,dog run"))
print(a_str)
b_str=''.join(sorted("Woof,Woof,dog run"))
print(b_str)           

運作結果為

nur god,fooW,fooW

,,WWdffgnoooooru

#Python在學習8# Python中字母大小寫轉換

第二組函數:

将十進制轉換為二進制、十六進制和八進制

Bin(n):十進制轉換為二進制,并在結果前自動添加“0b”标記

Hex(n):十進制轉換為十六進制,并在結果前自動添加“0x”标記

Oct(n):十進制轉換為八進制,并在結果前自動添加“0o”标記

例如運作以下代碼

print(bin(12),oct(12),hex(12))           
#Python在學習8# Python中字母大小寫轉換

顯示的結果為:

0b1100 0o14 0xc

第三組函數:字元串的布爾運算

String.isalnum(),字元串中至少有一個字元,并且字元全部為數字

String.isalpha(),字元串中至少有一個字元,并且字元全部為字母

String.isdecimal(),字元串中至少有一個字元,并且全部為十進制數

String.isdigit(),字元串中至少有一個字元,并且全部為十進制數

String.isidentifier(),字元串中至少有一個字元,第一個字元必須是字母或者下劃線,其他字母必須是字母、數字或者下劃線(類似于進階密碼的要求)

String.islower(),字元串中至少有一個字元,并且所有字母都是小寫

String.isprintable(),字元串中至少有一個字元,并且都是可列印的(不含\t、\n這類換行符等)

String.isspace(),至少一個字元,且所有字元均為空格

String.istitle(),至少有一個字元,且每個單詞都是有效的,即單詞首字母大寫,其他字母小寫,單詞之間可能有空白或者标點符号

String.isupper(),至少有一個字元,且每個字母都是大寫。

使用舉例代碼如下:

a_str="I went to school when I was 5 years old."
if a_str[0].isupper():
    print('first letter is uppercase.')
if a_str.isalpha():
    print('the sentence does not exit numbers')
else:
    print('the sentence has at least one number')
if a_str.isupper():
    print('all chars are uppercase')
else:
    print('not all chars are uppercase')
if a_str.istitle():
    print('quatifies as a title')
else:
    print('not quafilied as a title')           

對應的運作結果如下:

first letter is uppercase.

the sentence has at least one number

not all chars are uppercase

not quafilied as a title

在pycharm虛拟環境下的函數用法提示中,可以看到字元串的布爾方法的所有函數都可以被提示出來,大家可以充分的嘗試下每個函數的功能。

#Python在學習8# Python中字母大小寫轉換

第四組函數:大小寫轉換

String.lower() 将字元串中的所有字母轉換為小寫字母

String.upper() 将字元串中的所有字母轉換為大寫字母

String.title() 将字元串中的所有單詞首字母大寫,其他字母小寫并保持單詞間隔、符号等

String.swapcase()将字元串中的子母大小寫轉換

繼續看實際使用的代碼操作

a_str="I went to school when I was 5 years old."
b_str=a_str.lower()
c_str=a_str.upper()
d_str=a_str.title()
e_str=a_str.swapcase()
print(a_str)
print(b_str)
print(c_str)
print(d_str)
print(e_str)           

實際運作結果如下:

I went to school when I was 5 years old.

i went to school when i was 5 years old.

I WENT TO SCHOOL WHEN I WAS 5 YEARS OLD.

I Went To School When I Was 5 Years Old.

i WENT TO SCHOOL WHEN i WAS 5 YEARS OLD.

每個函數的直覺對比非常明顯。

#Python在學習8# Python中字母大小寫轉換

#加油!

#一點一滴的努力,未來都會有回報。

#歲月靜好,不去羨慕旁人,隻做好自己,花朵總會綻放。

#以上學習感悟來自于《高階Python代碼精進之路》([美]Brain Overland, John Bennett著,李輝,韓慧昌譯,中國工信出版集團電子工業出版社2022年4月出版)