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)
'^'

Example [edit]

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)

Or shorter (using list comprehension instead of the for block):

# 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)


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]