4. Strings
Syllabus :
Manipulating Strings: Working with Strings, Useful String Methods, Format operators , Project: Password Locker,
Project: Adding Bullets to Wiki Markup
4.1 Working with Strings :
A string is a sequence of characters. It can be created by enclosing characters in single or double or triple quotes.
Example : ‘Hello World!’ , “Python Programming“ , ”’apple”’
Creating a string :
Creating a string is as simple as assigning a value to variables as illustrated below :
var1 = 'Hello World!' var2 = "Python Programming" var3 = '''Water Melon'''
![](http://textcon.space/wp-content/uploads/2022/12/image-172.png)
Triple quotes can extend multiple lines as illustrated below :
![](http://textcon.space/wp-content/uploads/2022/12/image-173.png)
Length of a string
![](http://textcon.space/wp-content/uploads/2022/12/image-174.png)
One can get last letter of string using len( ) function as illustrated below :
![](http://textcon.space/wp-content/uploads/2022/12/image-175.png)
String Indexing
In Python string can be indexed in forward and backward direction as illustrated in the figure below :
![](http://textcon.space/wp-content/uploads/2022/12/image-168.png)
Consider a string name = ” Sophia“. Here string Sophia is made up of 6 characters. Each character of the string can be accessed by using either forward indexing or backward indexing as illustrated below:
![](http://textcon.space/wp-content/uploads/2022/12/image-171.png)
String Traversal
String traversal can be performed Using looping statements like for loop and while loop .
String traversal using while loop
![](http://textcon.space/wp-content/uploads/2022/12/image-176.png)
String traversal using for loop
![](http://textcon.space/wp-content/uploads/2022/12/image-177.png)
String traversal in reverse order
![](http://textcon.space/wp-content/uploads/2022/12/image-178.png)
Lists aren’t the only data types that represent ordered sequences of values.For example, strings and lists are actually similar, if you consider a string to be a “list” of single text characters. Many of the things you can do with lists can also be done with strings: indexing; slicing; and using them with for loops, with len(), and with the in and not in operators.