Introduction: Python Programming: Part 2
Python Programming Part 2
This Instructable is a little bit of everything about python Programming.
Step 1: Strings
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!' var2 = "Python Programming"
Accessing Values in Strings
Python does not support a character type; these are treated as strings of length one, thus also considered a substring. To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example:
var1 = 'Hello World!' var2 = "Python Programming" print var1 print var2[1:5]
This will produce the following:
You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example −
var1 = 'Hello World!' print "Updated String :- ", var1[:6] + 'Python'When the above code is executed, it produces the following result:
Updated String :- Hello Python
Following table is a list of escape or non-printable characters that can be represented with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
\b - - - BackSpace \n - - - Newline(Return) \r - - - Carriage Return \t - - - Tab \v - - - Vertical Tab \s - - - Space
More String Basics
print len("Hello, World!")
That prints out 12, because "Hello world!" is 12 characters long, including punctuation and spaces.
s = "Hello, World!" print s.index("o")
That prints out 4, because the location of the first occurrence of the letter "o" is 4 characters away from the first character. Notice how there are actually two o's in the phrase - this method only recognizes the first.
But why didn't it print out 5? Isn't "o" the fifth character in the string? To make things more simple, Python (and most other programming languages) start things at 0 instead of 1. So the index of "o" is 4.