Python basics string basics

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

# 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'>
# concatenation using "+"

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

String Indexing

# to locate a specific letter in a string
# python index starts with 0

a_letter = 'string'[3] 
print a_letter

Basic String Methods

# Check whether the string is made of letters

n = "Great"
y = "Gr8"

print n.isalpha()
print y.isalpha()
# 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

# %s
s = 'string'

print "Another Way to create %s, which is called %s formatting" %(a, a)
print "FYI: %s." %('')
Another Way to create string, which is called string formatting