Last modified on 21 May 2014, at 12:25

Python Programming/Text

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

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

You can slice strings just like lists and any other sequences:

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

To get the ASCII code of a character, use the ord() function.

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

To get the character encoded by an ASCII code number, use the chr() function.

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

ExampleEdit

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]

ExercisesEdit

  1. Use Python to determine the difference in ASCII code between lowercase and upper case letters.
  2. Write a program that converts a lowercase letter to an upper case letter using the ASCII code. (Note that there are better ways to do this, but you should do it once using the ASCII code to get a feel for how the language works)