Python str 字串用法與範例

本篇 ShengYu 要介紹 Python str 字串用法與範例,str 字串是 python 最基本的功能,以下為 Python str 字串的基本用法與範例。

以下 Python str 內容將分為這幾部份,

  • Python 字串基本用法
  • 字串連接
  • 讀取字串的元素,字串索引
  • 字串索引值為 -1 或 -n
  • for 迴圈遍歷巡訪字串裡的元素
  • 建立空字串
  • 字串切片
  • 字串切割
  • 字串去除空白
  • 用 str() 將其他類型轉為字串

Python 字串基本用法

Python 的字串語法為文字前後加上兩個單引號 '' 或兩個雙引號 "",例如:'hello world' 或者 "hello world",依個人喜好或情境來選擇使用,例如今天如果遇到字串裡有包含 ' 像是 "ShengYu's notebook",就使用兩個雙引號來表示字串。

Python 字串的變數類型為 str,可以使用 type() 來檢查變數類型得知。

Python 字串可以使用 len() 來計算字串的長度。

1
2
3
4
s = 'hello world'
print(s)
print(type(s))
print(len(s))

輸出結果如下,

1
2
3
hello world
<class 'str'>
11

字串連接

在 Python 上使用 + 加號來連接兩個字串,用法範例如下,

1
2
3
4
5
s1 = 'hello'
s2 = ' world'
s3 = s1 + s2
print(s3)
print('hello' + ' ' + 'world')

輸出結果如下,

1
2
hello world
hello world

讀取字串的元素,字串索引

這邊介紹字串索引或讀取字串裡的元素的方法

1
2
3
4
s = 'hello world'
print(s[0])
print(s[1])
print(s[2])

輸出結果如下,

1
2
3
h
e
l

字串索引值為 -1 或 -n

字串索引值是 -1 表示字串的最後一個元素,索引值是 -2 表示字串的倒數第二個元素,索引值是 -n 表示字串的倒數第n個元素,依此類推,

1
2
3
4
s = 'hello world'
print(s[-1])
print(s[-2])
print(s[-3])

輸出結果如下,

1
2
3
d
l
r

for 迴圈遍歷巡訪字串裡的元素

用 for 迴圈來遍歷巡訪字串 str 裡的所有元素並印出來,

1
2
3
s = 'hello world'
for i in s:
print(i)

輸出結果如下,

1
2
3
4
5
6
7
8
9
10
11
h
e
l
l
o

w
o
r
l
d

更多 for 迴圈用法請看這篇

建立空字串

建立空字串方式如下,

1
2
3
4
5
6
7
8
9
s1 = ''
print(s1)
print(type(s1))
print(len(s1))

s2 = str()
print(s2)
print(type(s2))
print(len(s2))

輸出結果如下,

1
2
3
4
5
6

<class 'str'>
0

<class 'str'>
0

字串切片

字串切片就是基於原本字串中取得某區間的元素,例如:前幾個元素或後幾個元素等等,用法範例如下,

1
2
3
4
5
6
s = 'hello world'
print(s[0:3]) # 字串索引值0到索引值3
print(s[2:7]) # 字串索引值2到索引值7
print(s[2:]) # 字串索引值2到最後
print(s[:7]) # 字串前7個元素
print(s[:]) # 字串所有元素

輸出結果如下,

1
2
3
4
5
hel
llo w
llo world
hello w
hello world

詳細的字串切片用法與範例可以看這篇

字串切割

字串切割也是常常用的的功能,簡單的字串切割空白作為分隔符號的用法範例如下,

1
2
s = 'hello world'
print(s.split())

輸出結果如下,

1
['hello', 'world']

詳細的字串切割用法與範例可以看這篇

字串去除空白

偶爾會需要將字串的空白或其他多餘的字元給去除,就要這樣使用,

1
2
s = ' hello world '
print(s.strip())

輸出結果如下,

1
hello world

詳細的字串去除空白或其他多餘的字元用法與範例可以看這篇

用 str() 將其他類型轉為字串

str() 可以將整數或浮點數或其他變數類型的資料轉換為字串,用法範例如下,

1
2
3
4
5
6
7
8
9
n = 123
s1 = str(n)
print(type(n))
print(s1)

f = 123.456
s2 = str(f)
print(type(f))
print(s2)

輸出結果如下,

1
2
3
4
<class 'int'>
123
<class 'float'>
123.456

下一篇將介紹 list 串列的用法

以上就是 Python str 字串用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 字串切片
Python 檢查 str 字串是否為空
Python 新手入門教學懶人包
Python list 串列用法與範例
Python set 集合用法與範例
Python dict 字典用法與範例
Python tuple 元組用法與範例