Python Strings

  1. Python supports both single and double quotes
  2. backslash (\) is used to escape characters
  3. when in the last position, backslash is a string continuation character
  4. \n is the newline character, \t is the tab character
  5. Strings surrounded with """ or ''' do not need to be escaped
  6. + concatenates string
  7. * multiplies string
  8. string_name[] is used for substring
  9. len() returns string length
  10. u creates a Unicode string
  11. r creates a raw string i.e. ignores \n, \r, etc.

Python String Example 1

print 'my code'			# my code
print 'Mike\'s code'	# Mike's code
print "Mike\'s code"	# Mike's code
# "Veni, Vidi, Vici", Julius Cesar
print '"Veni, Vidi, Vici", Julius Cesar'
# "Veni, Vidi, Vici", Julius Cesar
print "\"Veni, Vidi, Vici\", Julius Cesar"

Python String Example 2

print """
Veni, Vidi, Vici
- Julius Cesar
"I came, I saw, I conquered"
"""

Python String Example 3

s = "Dividing a very \
long line.\n\
Another line."
print s

Python String Example 4

# Julius Cesar
print 'Julius ' + 'Cesar'
# Muslims have to say 'I do' three times to get married
print 'I do! ' * 3

Python String Example 5

s = 'Veni, Vidi, Vici'
# fourth character, index starts with 0
print s[3]
# start from first character, print 4 characters
print s[0:4]
# start from sixth character, print till end
print s[6:]
# print the first 4 charcters
print s[:4]
# print the last character
print s[-1]

Python String Example 6

s = 'Veni, Vidi, Vici'
print len(s)	# 16