Python 字串增量方法
在本教程中,我們將學習在 Python 中遞增字元的不同方法。
型別轉換
讓我們首先看看在不進行型別轉換的情況下,將整數新增到字元會發生什麼。
示例
## str initialization char = "t" ## try to add 1 to char char += 1 ## gets an error
如果您執行上面的程式,它將產生以下結果:
TypeError Traceback (most recent call last) <ipython-input-20-312932410ef9> in <module>() 3 4 ## try to add 1 to char ----> 5 char += 1 ## gets an error TypeError: must be str, not int
要在 Python 中遞增字元,我們必須將其轉換為**整數**,然後為其加 1,最後將結果**整數**轉換為**字元**。我們可以使用內建方法**ord**和**chr**來實現這一點。
示例
## str initialization
char = "t"
## converting char into int
i = ord(char[0])
## we can add any number if we want
## incrementing
i += 1
## casting the resultant int to char
## we will get 'u'
char = chr(i)
print(f"Alphabet after t is {char}")如果您執行上面的程式,它將產生以下結果:
Alphabet after t is u
位元組
還有一種使用**bytes**遞增字元的方法。
- 將字串轉換為**bytes**。
- 結果將是一個數組,包含字串中所有字元的 ASCII 值。
- 為轉換後的**bytes**的第一個字元加 1。結果將是一個整數。
- 將**整數**轉換為**字元**。
示例
## str initialization
char = "t"
## converting char to bytes
b = bytes(char, 'utf-8')
## adding 1 to first char of 'b'
## b[0] is 't' here
b = b[0] + 1
## converting 'b' into char
print(f"Alphabet after incrementing ACII value is {chr(b)}")如果您執行上面的程式,它將產生以下結果:
Alphabet after incrementing ACII value is u
如果我們有一個字串並將其轉換為**bytes**,那麼我們可以遞增任何我們想要的字元。讓我們來看一個例子。
示例
## str initialization
name = "tutorialspoint"
## converting char to bytes
b = bytes(name, 'utf-8')
## adding 1 to 'a' char of 'b'
## 'a' index is 6
b = b[6] + 1
## converting 'b' into char
print(f"name after incrementing 'a' char is tutori{chr(b)}lspoint")如果您執行上面的程式,它將產生以下結果:
name after incrementing ‘a’ char is tutoriblspoint
我希望您能很好地理解這個概念。如果您對本教程有任何疑問,請在評論區提出。祝您程式設計愉快 :)
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP