Title: Python Basics: String Basics Date: 2017-10-26 13:26 Modified: 2017-10-30 13:26 Category: Python Tags: python, basics, string Slug: python-basics-string-basics Authors: Xiaoyue MA Summary: Basic string property and operations.

Creating a String


In [1]:
# three ways of creating a string

a = 'string'
b = "string"
c = str(3.14)

print a, type(a)
print b, type(b)
print c, type(c)


string <type 'str'>
string <type 'str'>
3.14 <type 'str'>

In [2]:
# concatenation using "+"

s = 'A ' + 'sentence ' + 'can '+'be made' + 'like this!'
print s


A sentence can be madelike this!

String Indexing


In [3]:
# to locate a specific letter in a string
# python index starts with 0

a_letter = 'string'[3] 
print a_letter


i

Basic String Methods


In [4]:
# Check whether the string is made of letters

n = "Great"
y = "Gr8"

print n.isalpha()
print y.isalpha()


True
False

In [5]:
# Convert string to lower or upper cases

l = 'lower'
u = 'UPPER'
m = 'mIxEd'

print l.upper(), l.lower()
print u.upper(), u.lower()
print m.upper(), m.lower()


LOWER lower
UPPER upper
MIXED mixed

String Formatting


In [6]:
# %s
s = 'string'

print "Another Way to create %s, which is called %s formatting" %(a, a)
print "FYI: %s." %('https://docs.python.org/2/library/stdtypes.html#string-formatting')


Another Way to create string, which is called string formatting
FYI: https://docs.python.org/2/library/stdtypes.html#string-formatting.