python中字符串的常見操作(一)


如有字符串:

str1 = '192.168.1.1'
str2 = 'asdfghjk'
str3 = 'Asd fg hj ki'
str4 = ' '
str5 = ''

以下是常見操作:
# isalpha()判斷字符串是否是字符

>>> res = str1.isalpha()
>>> print(res)
False

# isalnum()判斷是否是數字或者字符組成

>>> res = str1.isalnum()
>>> print(res)
False

# isdigit()判斷是否是整數

>>> res = str1.isdigit()
>>> print(res)
False

#rfind()從右往左找第一個對應的值,顯示的是正向索引,如果沒找到匹配的值返回-1

>>> res = str1.rfind('.',0,3)
>>> print(res)
-1
>>> res = str1.rfind('.')
>>> print(res)
9

# find()從左往右找第一個對應的值,顯示的是正向索引,如果沒找到匹配的值返回-1

>>> res = str1.find('.',0,3)
>>> print(res)
-1
>>> res = str1.find('.')
>>> print(res)
3

# index()從左往右找第一個對應的值,顯示的是正向索引,如果沒找到匹配的值報錯

>>> res = str1.index('.')
>>> print(res)
3
>>> res = str1.index('.',0,4)
>>> print(res)
3
>>> res = str1.index('.',4,8)
>>> print(res)
7
>>> res = str1.index('12')
>>> print(res)
res = str1.index('12')
ValueError: substring not found 

# count()顯示字符個數,如果沒有顯示0

>>> res = str1.count('q')
>>> print(res)
0
>>> res = str1.count('1')
>>> print(res)
4
>>> res = str1.count('1',0,6)
>>> print(res)
2
>>> res = str1.count('16')
>>> print(res)
1

#把字符串變成抬頭(每個單詞的開頭變成大寫,數字不會報錯)

>>> res = str1.title()
>>> print(res)
192.168.1.1
>>> res = str2.title()
>>> print(res)
Asdfghjk
>>> res = str3.title()
>>> print(res)
Asd Fg Hj Ki

#判斷字符串當中開頭字符是否為所選的字符

>>> res = str1.startswith('1')
>>> print(res)
True
>>> res = str2.startswith('A')
>>> print(res)
False
>>> res = str3.startswith('A')
>>> print(res)
True

#判斷字符串當中結尾字符是否為所選的字符

>>> res = str3.endswith('ki')
>>> print(res)
True
>>> res = str3.endswith('j ki')
>>> print(res)
True
>>> res = str3.endswith('jki')
>>> print(res)
False 

#isspace判斷是否是由空格組成

>>> res = str3.isspace()
>>> print(res)
False
>>> res = str4.isspace()
>>> print(res)
True
>>> res = str5.isspace()
>>> print(res)
False 

pycharm快捷鍵
  # ctrl + d:復制一行
  # ctrl + ?:快速注釋一行|撤銷
  # tab鍵:縮進4個空格
  # shift+tab鍵:回退4個空格


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM