Python 文字序列型別


在 Python 中,str 物件處理文字或字串型別資料。字串是不可變的。字串是 Unicode 字元的序列。我們可以使用單引號、雙引號或三引號來定義字串字面量。

  • ‘這是一個用單引號括起來的字串’
  • “另一個用雙引號括起來的文字”
  • ‘’’使用三個單引號的文字’’’ 或 “””使用三個雙引號的文字”””

我們可以使用三引號在 Python 中賦值多行字串。

有不同的與字串相關的函式。一些字串方法如下:

序號 操作/函式和描述
1

s.capitalize()

將第一個字元轉換為大寫字母

2

s.center(width[, fillchar])

用指定字元填充字串。預設為 ' ' <空格>

3

s.count(sub[, start[, end]])

計算字串中出現的次數

4

s.find(sub[, start[, end]])

返回文字中子字串的第一次出現位置

5

s.format(*args, **kwargs)

格式化字串以生成良好的輸出

6

s.isalnum()

檢查字母數字字元

7

s.isalpha()

檢查所有字元是否都是字母

8

s.isdigit()

檢查數字字元

9

s.isspace()

檢查字串中的空格

10

s.join(iterable)

連線字串

11

s.ljust(width[, fillchar])

返回左對齊的字串

12

s.rjust(width[, fillchar])

返回右對齊的字串

13

s.lower()

轉換為小寫字母

14

s.split(sep=None, maxsplit=-1)

用給定的分隔符分割字串

15

s.strip([chars])

從字串中剪下字元

16

s.swapcase()

將小寫轉換為大寫,反之亦然

17

s.upper()

轉換為大寫字母

18

s.zfill(width)

透過在其前面新增零來轉換字串。

示例程式碼

即時演示

myStr1 = 'This is a Python String'
myStr2 = "hello world"

print(myStr2)
print(myStr2.capitalize())

print(myStr2.center(len(myStr1)))
print(myStr1)

print(myStr1.find('Py')) #The location of substring Py.
myStr3 = 'abc123'
print(myStr3.isalnum())
print(myStr3.isdigit())

print('AB'.join('XY'))
print(myStr2.rjust(20, '_')) #Right justified string, filled with '_' character
print(myStr1.swapcase())

print('2509'.zfill(10)) #Fill 0s to make 10 character long string

輸出

hello world
Hello world
      hello world      
This is a Python String
10
True
False
XABY
_________hello world
tHIS IS A pYTHON sTRING
0000002509

更新於: 2019-07-30

647 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.