Python Programming/Text

From Wikibooks, open books for an open world
< Python Programming
Jump to: navigation, search

To get the length of a string, we use the len() function:

len("Hello Wikibooks!") -> 16

You can take bits of a string using the [:] command, much like lists.

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

To get an ASCII character code, you use the ord()command.

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

To get the letter formed by an ASCII character code, you use the chr() command.

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

[edit] Example

stringparser.py

# python3.2
# Add each character, and it's ordinal, of user's text input, to two lists
s = input("Enter value: ")
L1 = [] 
L2 = []
for c in s:   #a shorter way of saying for c in range(1, s)
    L1.append(c) 
    L2.append(ord(c))
print(L1)
print(L2)

Output:

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

Or

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]
Personal tools
Namespaces

Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export