Python--字串

來源:互聯網
上載者:User

標籤:找不到   替換   tar   list   空格   下標   字串   返回   重要   

# 字串的方法不會改變原字串的值
name = ‘ besttest ‘
print(name.strip()) # 預設去掉兩邊的空格和分行符號
print(name)

print(‘ 123 456‘.strip(‘456‘))

new_name = name.lstrip() # 去掉左邊的空格和分行符號
new_name1 = name.rstrip() # 去掉右邊的空格和分行符號
print(name.count(‘t‘))  # 尋找某個字串在裡面出現的次數
print(name.count(‘o‘))
name = ‘besttest‘
print(name.capitalize()) # 首字母大寫

print(name.center(50, ‘*‘)) # 把字串放中間,總長度為50,以*補全
print(name.find(‘t‘))  # 找到t,返回第一次出現的下標
print(name.find(‘o‘)) # 如果不存在,返回-1

print(name.index(‘t‘))
# print(name.index(‘o‘)) # 找不到時候報錯!

print(name.upper())  # 小寫字母變大寫
print(name.lower()) # 大寫字母變小寫

name = ‘a.txt‘
print(name.endswith(‘txt‘)) # 返回True或者False,字串是否以什麼結尾
print(name.startswith(‘a‘)) # 返回True或者False,字串是否以什麼開頭

f = ‘{name}歡迎光臨‘
print(f.format(name=‘wangsilei‘)) # 字串格式化

f = ‘{name}歡迎光臨,{age}‘
d = {‘name‘: ‘panda‘, ‘age‘: 18}
print(f.format_map(d))
name = ‘abcde‘
print(name.replace(‘abc‘, ‘123‘)) # 字串替換

print(‘123456‘.isdigit()) # 是否是數字
print(‘abc‘.isupper()) # 判斷是否全部是大寫字母
print(‘abc‘.islower()) # 判斷是否全部是小寫字母

print(‘abc123‘.isalnum()) # 是否包含數字或字母(只有數字或者字母組合)
print(‘abA‘.isalpha()) # 是否是英文字母
# 字串重要的方法
str1 = ‘a, b, c, d, e, f, g‘
print(str1.split(‘, ‘))
print((str1.split(‘, ‘))) # 字串分割,返回一個list
print((str1.split(‘b‘)))
print((str1.split())) # 不寫預設空格分隔

slit = [‘a‘, ‘b‘, ‘c‘, ‘d‘]
name = ‘,‘.join(slit) # 通過,連結list裡面的每一個值
print(name)

s2 = ‘hhhhhhhhh‘
print(‘*‘.join(s2))

d = {‘name‘: ‘wangsilei‘, ‘age‘: 18}
print(‘*‘.join(d)) # 只對key有效

name = ‘abcde‘
print(‘a‘ in name)
print(‘e‘ not in name)

Python--字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.