python字符串的操作

 

轉載:https://www.cnblogs.com/hukey/p/9612961.html

字符串的操作方法:

1.   capitalize() :首字母大寫

s1 = 'my heart will go on'
print(s1.capitalize())  # 首字母大寫

# 執行結果:
# My heart will go on

2   upper() : 全部大寫

s1 = 'my heart will go on'
print(s1.upper())   # 全部轉爲大寫

# 執行結果:
# MY HEART WILL GO ON

3   lower() : 全部小寫

4  title(): 標題首字母大寫

5  center(): 居中,默認填充空格

6   count():統計字符串出現個數 

s1 = 'adfasdfasdfasdfertadf'
print(s1.count('a'))    # 統計字符串出現的次數

# 執行結果:
# 5

7  split(): 按照指定字符分隔成多個元素  str --> list

s1 = 'nice to meeting you'
print(s1.split())   # 默認將字符串通過空格分隔並組成列表類型

# 執行結果:
# ['nice', 'to', 'meeting', 'you']

9  replace(): 字符串替換

s1 = 'nice to meeting you'
print(s1.replace('meeting', 'see')) # 在字符串中,用第一個參數替換掉第二個參數,默認是匹配上則全部替換

# 執行結果:
# nice to see you

10 find() 和 index()

find() 和 index() 都是通過元素找索引的方法,區別如下:

find()方法:元素存在打印索引,元素不存在返回 -1

index()方法:元素存在打印索引,元素不存在報錯。錯誤信息:ValueError: substring not found

複製代碼

s1 = 'nice to meeting you'

print(s1.find('to'))

# 執行結果:
# 5

print(s1.find('xxx'))

# 執行結果:
# -1

print(s1.index('to'))

# 執行結果:
# 5

# print(s1.index('xxx'))

# 執行結果:
# ValueError: substring not found
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章