Milandeep Bassi

How to Manipulate Strings in Python Programming

25th, January, 2020


Index Numbers

Each character in a string can be accessed separately. Each character has a number reference to it. The index number always begins at 0. 

name = "Code Easy"
name[0] = C
name[1] = o
name[2] = d
name[3] = e
name[4] =
name[5] = E
...

An example of this could be a program that selects a character of a users inputted name.

name = input("Enter a name: ")
print ("Name:", name)
x = int(input("Enter a number: ")
print("Index number", x,"is", name[x])

We can also use what you learned from lesson #3 about while loops to create a program that shows the index numbers of the user.

name = input("Enter a name: ")
x = 0 # x = Index
while x < len(name):
print ("Index", x, "is", name[x])
x = x + 1

However in this example using a for loop is quicker to print the letters in a word. 

name = input("Enter a name: ")
for x in name:
print(x)

You can also have negative index numbers.

name = "Code Easy"
name[-1] = y
name[-2] = s
...

You can also index a range of character by using a colon (:). To do this you would do [x:x]. You can also change the ways some strings are printed as seen below.

name = "code easy"
phone = "Samsung"
capitalize = name.capitalize()
title = name.title()
upper = name.upper()
lower = phone.lower()
print(capitalize)
print(title)
print(upper)
print(lower)

>>>
Code easy
Code Easy
CODE EASY
samsung
>>>

Some other ways to manipulate strings is to find letters in words or to count the number of times a character is repeated. You can also split characters after certain letters or into individual words. 

name = "Code Easy"
First_e = name.find("e") # Index of First e
Count_e = name.count("e") # Amount of e's in word
print(First_e)
print(Count_e)
print(name.split())
print(name.split("d"))

>>>
32
['Code', 'Easy']
['Cod', 'asy']
>>>

Try these strings manipulations out yourself to understand them better!