日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

詳解python字符串相關str_python

作者:cw_hstx ? 更新時間: 2022-03-29 編程語言

1:訪str單個字符

#for循環迭代
name = 'Chengwei'
for ch in name:
    print(ch, end=' ')
#C h e n g w e i
#索引
print(name[1])
#h
print(name[-1]) #最后一個為 -1
#i
#len()函數返回str字符串數量
print(len(name))
#8

2: 字符串連接

message = 'hello' + 'world'
print(message)
#helloworld

3:str切片

message = 'helloworld'
print(message[2:4])
#ll

4:使用in 和not in 測試字符串

message = 'helloworld'
if 'hello' in message:
    print('YES')
#YES
if 'aaa' not in message:
    print('YES')
#YES

5:str方法

字符串測試方法

isalnum() 如果str只包含字母或數字,并且長度至少為一個字符,則返回true。否則返回false
isalpha() 如果str只包含字母并且長度至少為一個字符,則返回true。否則返回false
isdigit() 如果str只包含數字如果str只包含字母并且長度至少為一個字符,則返回true。否則返回false
islower()

如果str中的所有字母都是小寫如果str只包含數字如果str只包含字母并且長度至少為一個字符,則返回true。否則返回false

isspace() 如果str只包含空白字符,并且長度至少為一個字符,則返回true。否則返回false(空格,\n,\t)
isupper()

如果str中的所有字母都是大寫如果str只包含數字如果str只包含字母并且長度至少為一個字符,則返回true。否則返回false

字符串修改方法

lower() 返回將所有字母轉換為小寫的str副本。不是字母的不變
lstrip() 返回刪除所有前導空白字符的str副本。
lstrip(str_item) str_item是字符串。返回刪除所有前導str_item的字符串副本
rstrip() 返回所有尾部空白字符串的字符串副本。
rstrip(str_item) 返回刪除所有尾部str_item的字符串副本
strip() ?
strip(str_item) 刪除所有前導和尾部str_item的字符串副本
upper() ?
lower() 返回將所有字母轉換為小寫的str副本。不是字母的不變
lstrip() 返回刪除所有前導空白字符的str副本。
lstrip(str_item) str_item是字符串。返回刪除所有前導str_item的字符串副本
rstrip() 返回所有尾部空白字符串的字符串副本。
rstrip(str_item) 返回刪除所有尾部str_item的字符串副本
strip() ?
strip(str_item) 刪除所有前導和尾部str_item的字符串副本
upper() ?

搜索和替換的方法

endswith(substring) 返回true或false
find(substring) 返回找到substring的最小索引位置。沒有找到返回 -1
replace(old, new) 返回將所有的old替換為new的字符串副本
starstwith(substring) 返回true或false

6:重復操作符

print('hello' * 2)
#hellohello

7:分割字符串

message = 'hello world chengwei'
message_list = message.split()
print(message_list)
#['hello', 'world', 'chengwei']
message = 'hello,world,chengwei'
message_list = message.split(',')
print(message_list)
#['hello', 'world', 'chengwei']

總結

原文鏈接:https://blog.csdn.net/cw_hstx/article/details/122517790

欄目分類
最近更新