Skip to main content

Command Palette

Search for a command to run...

Day09 - String in Python

String, Use of Backslash, Multiline, Indexing, Looping

Updated
2 min read
Day09 - String in Python
C
I am Data Science student, has a little bit knowledge on Web Development. I also love writing and editing as my hobby. Passionate to explore the world.

Strings in Python:

String is a collection of alphabets, words or other characters. It is a sequence of characters. Or anything enclosed in single or double quote is known as "string".

Example - Using double quote

data = "Python Language"  #using double quote
print(data)
print(type(data))   #channing rule

data = 'Python Language'  #using single quote
print(data)
print(type(data))   #channing rule

Output:

Python Language
<class 'str'>

Python Language
<class 'str'>

Quotation marks in between string - Use of \

Backslash - use to convert special character into normal character.

data = 'Python Language\ 123 "Hello world"'
print(data)
print(type(data))

Output:

Python Language 'Hello world
<class 'str'>

Multiline string:

A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string.

Example:

b = """Line1 python
Line2 python
Line3 python """ 
print(b) #triple double quote
print(type(b))

Output:

Line1 python
Line2 python
Line3 python
<class 'str'>

Indexing:

It is ' accessing characters of a string. In python string is like an array of characters (not exactly).

name = "Python"
print(name[0]) #output = P
print(name[1]) #output = y
print(name[2]) #output = t
print(name[3]) #output = h
print(name[4]) #output = o
print(name[5]) #output = n
#print(name[5])   #throws index error - b/c there is nothing at 6.

Output:

P
y
t
h
o
n

Looping through the string:

for loop - characters print all the characters of string.

Example:

name = "Python"
for character in name:
    print(character)

Output:

P
y
t
h
o
n

Key Points:

  • \t - use to create 4spaces in string.

  • \n - use to add new line in string.

  • Triple single quotes or Triple double quotes are the boundaries of a string.

<< Previously ---------------------------------------------------- Next Lesson >>

100DaysofPython

Part 10 of 35

This series is for beginners in which we explore python language along with how it is used in data science and do some exercises and some python related projects.

Up next

Day10 - String Slicing

Length of String, Positive & Negative Slicing