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]