And now presenting a cool trick that can be done with strings:
def shout(string): for character in string: print("Gimme a "+character) print("'"+character+"'") shout("Lose") def middle(string): print("The middle character is:", string[len(string)//2]) middle("abcdefg") middle("The Python Programming Language") middle("Atlanta")
And the output is:
Gimme a L 'L' Gimme a o 'o' Gimme a s 's' Gimme a e 'e' The middle character is: d The middle character is: r The middle character is: aWhat these programs demonstrate is that strings are similar to lists in several ways. The shout procedure shows that for loops can be used with strings just as they can be used with lists. The middle procedure shows that that strings can also use the len function and array indexes and slices. Most list features work on strings as well.
The next program demonstrates some string specific features:
def to_upper(string): ## Converts a string to upper case upper_case = "" for character in string: if 'a' <= character <= 'z': location = ord(character) - ord('a') new_ascii = location + ord('A') character = chr(new_ascii) upper_case = upper_case + character return upper_case print(to_upper("This is Text"))with the output being:
THIS IS TEXTThis works because the computer represents the characters of a string as numbers from 0 to 255 (or more if they are Unicode). Python has a function called ord (short for ordinal) that returns a character as a number. There is also a corresponding function called chr that converts a number into a character. With this in mind, the program should start to be clear. The first detail is the line:
if 'a' <= character <= 'z':
which checks to see if a letter is lower case. If it is, then the next lines are used. First it is converted into a location so that a=0, b=1, c=2 and so on with the line: location = ord(character) - ord('a')
. Next the new value is found with new_ascii = location + ord('A')
. This value is converted back to a character that is now upper case. And for what it is worth, Python does have a built-in string functions upper and lower for making upper and lower case strings.
Now for some interactive typing exercise:
>>> #Integer to String ... >>> 2 2 >>> str(2) '2' >>> -123 -123 >>> str(-123) '-123'
>>> #String to Integer ... >>> "23" '23' >>> int("23") 23 >>> "23"*2 '2323' >>> int("23")*2 46 >>> int(23.4) 23
>>> #Float to String ... >>> 1.23 1.23 >>> str(1.23) '1.23'
>>> #Float to Integer ... >>> 1.23 1.23 >>> int(1.23) 1 >>> int(-1.23) -1
>>> #String to Float ... >>> float("1.23") 1.23 >>> "1.23" '1.23' >>> float("123") 123.0
If you haven't guessed already, the function str
can convert a integer to a string and the function int
can convert a string (or a float) to an integer. The function float can convert a string (or an integer) to a float. The str
function returns a printable representation of something. Here are some examples of this:
>>> str(1) '1' >>> str(234.14) '234.14' >>> str([4, 42, 10]) '[4, 42, 10]'
One useful string function is the split
function that is part of any string. Here's the example:
>>> "This is a bunch of words".split() ['This', 'is', 'a', 'bunch', 'of', 'words'] >>> "First batch, second batch, third, fourth".split(",") ['First batch', ' second batch', ' third', ' fourth']Notice how
split
converts a string into a list of strings. The string is split by spaces by default or by the optional second argument (in this case, a comma).
One more feature is worth mentioning. Python strings can have escape sequences that allow characters that otherwise might be hard to insert in a string. Here is a table giving some examples:
What it makes | |
\' |
' |
\" |
" |
\\ |
\ |
\n |
newline |
\t |
tab |
\x6A |
j (lets a character be specified by a hex byte) |
\u2661 |
|
\U00002661 |
|
\N{white heart suit} |
#This program requires a excellent understanding of decimal numbers def to_string(in_int): "Converts an integer to a string" out_str = "" prefix = "" if in_int < 0: prefix = "-" in_int = -in_int while in_int // 10 != 0: out_str = chr(ord('0')+in_int % 10) + out_str in_int = in_int // 10 out_str = chr(ord('0')+in_int % 10) + out_str return prefix + out_str def to_int(in_str): "Converts a string to an integer" out_num = 0 if in_str[0] == "-": multiplier = -1 in_str = in_str[1:] else: multiplier = 1 for x in range(0, len(in_str)): out_num = out_num * 10 + ord(in_str[x]) - ord('0') return out_num * multiplier print(to_string(2)) print(to_string(23445)) print(to_string(-23445)) print(to_int("14234")) print(to_int("-3512"))
The output is:
2 23445 -23445 14234 -3512