跳至內容

Python/文本

維基教科書,自由的教學讀本

得到字符串長度:

>>> len("Hello Wikibooks!")
16

切片字符串:

>>> "Hello Wikibooks!"[0:5]
'Hello'
>>> "Hello Wikibooks!"[5:11]
' Wikib'
>>> "Hello Wikibooks!"[:5] #equivalent of [0:5]
'Hello'

得到字符的ASCII值:

>>> ord('h')
104
>>> ord('a')
97
>>> ord('^')
94

得到ASCII值所對應的字符:

>>> chr(104)
'h'
>>> chr(97)
'a'
>>> chr(94)
'^'

isalnum()返回真,如果字符串至少有一個字符,且所有字符都是數字字母。函數isalpha()類似

例子

[編輯]

stringparser.py

# Add each character, and it's ordinal, of user's text input, to two lists
s = input("Enter value: ")  # this line requires Python 3.x, use raw_input() instead of input() in Python 2.x
l1 = [] 
l2 = []
for c in s:   # in Python, a string is just a sequence, so we can iterate over it!
    l1.append(c) 
    l2.append(ord(c))
print(l1)
print(l2)

更簡明方式:

# Add each character, and it's ordinal, of user's text input, to two lists
s = input("Enter value: ")  # this line requires Python 3.x, use raw_input() instead of input() in Python 2.x

l1=[c for c in s]   # in Python, a string is just a sequence, so we can iterate over it!
l2=[ord(c) for c in s]

print(l1)
print(l2)


輸出:

Enter value: string
['s', 't', 'r', 'i', 'n', 'g']
[115, 116, 114, 105, 110, 103]

Enter value: Hello, Wikibooks!
['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'i', 'k', 'i', 'b', 'o', 'o', 'k', 's', '!']
[72, 101, 108, 108, 111, 44, 32, 87, 105, 107, 105, 98, 111, 111, 107, 115, 33]