Python基础数据类型之字符串(一)
生活随笔
收集整理的這篇文章主要介紹了
Python基础数据类型之字符串(一)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python基礎數據類型之字符串(一)
- 一、字符串格式化
- 1.字符串占位符
- 2.字符串格式化操作
- 二、f-string格式化
- 三、字符串的索引
- 四、字符串的切片
- 1.常規切片使用方法
- 3.步長的介紹
- 2.切片使用方法二
一、字符串格式化
1.字符串占位符
# %s 字符串占位 # %d 占位整數 # %f 占位小數2.字符串格式化操作
# 1.字符串格式化 # 姓名、年齡、地址、愛好 name = input("please enter your name:") address = input("please enter your address:") age = int(input("please enter your age:")) hobby = input("please enter your hobby:") # s = "我叫%s,我住在%s,我今年%d歲,我喜歡%s" % (name, address, age, hobby) s1 = "我叫{},我住在{},我今年{}歲,我喜歡做{}".format(name, address, age, hobby)print(s1) D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基礎/02_python基礎類型/02_字符串.py please enter your name:kitty please enter your address:wuhan please enter your age:18 please enter your hobby:HCIE 我叫kitty,我住在wuhan,我今年18歲,我喜歡HCIEProcess finished with exit code 0二、f-string格式化
f-string 是 python3.6 之后版本添加的,稱之為字面量格式化字符串。
# 姓名、年齡、地址、愛好 name = input("please enter your name:") address = input("please enter your address:") age = int(input("please enter your age:")) hobby = input("please enter your hobby:")# s = "我叫%s,我住在%s,我今年%d歲,我喜歡做%s" % (name, address, age, hobby) # s1 = "我叫{},我住在{},我今年{}歲,我喜歡做{}".format(name, address, age, hobby) s2 = f"我叫{name},我住在{address},我今年{age}歲,我喜歡做{hobby}" print(s2) D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基礎/02_python基礎類型/02_字符串.py please enter your name:kitty please enter your address:hangzhou please enter your age:18 please enter your hobby:HCIE 我叫kitty,我住在hangzhou,我今年18歲,我喜歡做HCIEProcess finished with exit code 0三、字符串的索引
索引:可以采用索引的方式來提取字符
# 可以采用索引的方式來提取摸個字符 s = "我要學習python" print(s[3]) print(s[0]) print(s[-1]) #表示倒數 D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基礎/02_python基礎類型/03_字符串的索引和切片.py 習 我 nProcess finished with exit code 0四、字符串的切片
切片:從一個字符串提取一部分內容。
1.常規切片使用方法
s = "我要學習python,還要學習RHCE" print(s[3:6]) # 從索引3為止切片,到位置6結束,但是拿不到位置6 print(s[0:10]) print(s[:10]) # 從開頭切,可以省略 print(s[11:]) # 從開始到結尾切片 print(s[-4:-1]) # 只能從左往右切片 print(s[-1:-4]) # 沒有結果 D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基礎/02_python基礎類型/03_字符串的索引和切片.py 習py 我要學習python 我要學習python 還要學習RHCE RHCProcess finished with exit code 03.步長的介紹
其實呢,step在這里表示的是切片的步長(step不能為0,默認為1)。
若 step > 0, 則表示從左向右進行切片。此時,start必須小于end才有結果,否則為空。
若 step < 0, 則表示從右向左進行切片。 此時,start必須大于end才有結果。
2.切片使用方法二
s = "我要學習python,還要學習RHCE" # 可以給切片添加步長來控制切片的方向 print(s[::-1]) # 負號表示從右往左 m = "adjapwqstm" print(m[4:9:2]) D:\soft\python\python.exe D:/soft/pycharm/pycharmfile/py基礎/02_python基礎類型/03_字符串的索引和切片.py ECHR習學要還,nohtyp習學要我 pqtProcess finished with exit code 0總結
以上是生活随笔為你收集整理的Python基础数据类型之字符串(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Docker容器原理及相关知识
- 下一篇: Python基础数据类型之字符串(二)