Python Basics 2 - String Methods, Place Holders and raw_input
Basics of Python (String Methods, raw_input & Place Holders)
Strings
Strings are sequences of characters without inherent values but can contain meaningful characters.
Example:
print 'That's a pretty bad string'
Syntax error occurs due to unescaped single quote.
Common Backslash Commands
Specific characters can be inserted into strings using backslash commands:
\- Inserts a backslash\n- Inserts a new line\t- Inserts a tab space
String Examples
Escaping Characters:
Using backslash to include an apostrophe:
Example:
print 'That\'s a pretty GOOD string'Output:
That's a pretty GOOD string
New Lines:
Using
\nfor line breaks:Example:
print 'This string\nis on multiple lines'Output:
This string is on multiple lines
Tabs:
Using
\tfor tab spaces:Example:
print 'This string\thas a tab.'Output:
This string has a tab.
String Indexes
Each character in a string has an index, starting from 0.
Example:
For string
dog = 'I am Sam', the character positions are:I (0) a (1) m (2) S (3) a (4) m (5)
Access characters using their index:
dog[0]returnsIdog[3]returnsS
Accessing String Characters
You can access string characters using index numbers:
Example:
dog = 'This is a Sample String'print dog[0]outputsTprint dog[7]outputsi
Storing String Characters in Variables
Characters can be stored in variables:
Example:
cat = dog[0](stores the first characterT).print catoutputsT
String Methods
Python offers various methods to manipulate strings:
len(dog)- Calculates the length of the stringdog.upper()- Converts string to uppercasedog.lower()- Converts string to lowercaseExample of method usage:
length = len(dog)big = dog.upper()small = dog.lower()
String Concatenation
Concatenation is the process of joining strings using the
+operator:Example:
who = 'I ' do = 'like to eat ' what = 'pizza!' print who + do + what
The output will be:
I like to eat pizza!
Type Casting in Concatenation
Non-string variables must be casted to strings:
Example:
pi = 3.1415print 'I like to eat ' + str(pi) + '!'Output:
I like to eat 3.1415!
Obtaining User Input with raw_input
Use
raw_input()to get user input:Example:
name = raw_input('What is your name?')When user inputs 'Sam', it outputs:
Your name is Sam
Casting User Input
Raw input is returned as a string; convert to int or float if necessary:
Example:
first_numb = raw_input('First Number?') second_numb = raw_input('Second Number?') product = int(first_numb) * int(second_numb) print 'Their product is ' + str(product)Inputting 5 and 12 outputs:
Their product is 60.
String Formatting with %
Use placeholders for formatting strings:
%s(string),%f(float),%d(integer)
Example:
string_1 = 'Camelot' string_2 = 'place' print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)Outputs:
Let's not go to Camelot. 'Tis a silly place.