1. 程式人生 > 其它 >Python基礎(一)

Python基礎(一)

一.字串

  1. 字串的簡單介紹
    字串是python中常用的資料型別之一,常用單引號或雙引號括起來。
    name="python" #單引號 name="python" #雙引號
    2.常用轉義字元:
    \n #換行符
    \t #橫向製表符
    \r #回車
    \v #縱向製表符
    3.字串的輸入和輸出
    3.1字串輸出
    print() #輸出函式
    格式化輸出:
    第一種方式:
    print('今天是%s年%s月%s日'%(2021,22,21))
    第二種方式:
    print('今天是{}月{}日'.format(11,24))
    第三種方式:
    print('今天是%{0}s年%{1}s月%{2}s日'%{'0':2021,'1':11,'2':24})

    注意:在格式化輸出的時候,要多加一個%號
    msg = '我叫%s,今年%d,我的學習進度1%%' % ('關亮和', 28)
    print(msg)
    3.2字串輸入
    input() #輸入函式
    name=input('請輸入你的名字:')
    4.字串內建函式
    1.find #通過元素找索引,找到第一個就返回,沒有就返回-1。
    today='hello wrold!'
    print(today.find('w')) #索引預設從0開始,空格佔用一個字元

6
2.index #通過元素找索引,找到第一個就返回,沒有就報錯。
today='hello wrold!'
print(today.index('e'))


1
3.upper #返回大寫字串
today='hello wrold!'
print(today.upper())
HELLO WROLD!
4.lowwer #返回小寫字串
today='hello wrold!'
print(today.lower())
hello wrold!
5.startswitch #判斷字串是否以指定字串開頭
today='hello wrold!'
print(today.startswith('h'),type(today.startswith('h')))
True <class 'bool'> #返回的資料型別為bool型別
6.endswitch #判斷字串是否以指定字串結尾
today='hello wrold!'

print(today.endswith('d'))
False
7.splite #指定字元分隔符
fruit='apple,peach,banana'
list=fruit.split('_')
print(list) #返回的資料型別為列表
['apple,peach,banana']
8.strip #去字串函式,
s=' abc ' print(s.strip()) #預設刪除空白字串 abc name='chensir' print(name.strip('chen')) #刪除指定字元 sir 9.replace #用來查詢替換 name='chensir'
print(name.replace('chen','li'))
lisir
10.count #統計當前字元在字串中出現的次數
s='safhjjjjjksdf'
print(s.count('j'))
5
11.title #每個單詞的首字母大寫
name='chensir,lisir'
print(name.title())
Chensir,Lisir
12.center #字串居中前後填充的自定義字元
today='hello word!'
print(today.center(20)) #居中對齊,以空格進行填充 print(today.center(20,'='))#居中對齊,以=號進行填充
hello word!
hello word!=
today='hello word!'
print(today.ljust(10,'=')) #左對齊
print(today.rjust(10,'=')) #右對齊
13.swapcase #大小寫翻轉
name='CHENsir'
print(name.swapcase())
chenSIR
14.join #自定製連線符,將可迭代物件中的元素連線起來
s='a,b,c'
print('_'.join(s))
a_,b,_c
15.capitalize #字串首字母大寫
name='chensir'
print(name.capitalize())
Chensir
5.字串運算子
| 操作符 | 描述 |例項 |
|+ | 字串連線 | a='hello' b='world' a+b='hello world'|
| * |重複輸出字串 | a*2='hellohello' |
| in | 測試一個字元在另一個字串中 | 'h' in a |
| not in |測試一個字元不在另一個字串中 |'h' not in a |