Strings

'''

In python, anything that is enclosed between a single or double quotation marks is considered as a string.

A string is generally a sequence or array of textual data.

It does not matter whether we enclose our strings between single or double quotes, the output remains same.

If there are some textual data that are enclosed within triple single quotes or triple double quotes, that is also considered as a string.

To convert a single line into a string, we can use either single quotes or double quotes or triple single quotes or tiple double quotes.

To convert multiple lines into a string, we can only use either triple single quotes or triple double quotes.

'''

name = "Sindhu"
friend = 'Rohan'
print("Hello, "+ name)      #output = Hello, Sindhu
#Plus is used to connect the strings as they are.

#apple = "He said, "I want to eat an apple.""   #output = error
# We cannot put double quotes inside double quotes.


apple = "He said, \"I want to eat an apple.\""
print(apple)      #output = He said, "I want to eat an apple."

APPLE = 'He said, "I want to eat an apple."'
print(APPLE)      #output = He said, "I want to eat an apple."  
# We can either use escape sequence character for double quotes inside double quotes or we can use double quotes inside single quotes.


'''Strings can be used in multiple lines also.
Friend = 'He said,
Hi Sindhu
How are you
"I want to eat an apple."'
print(Friend)        #output = error
There will be an error in unterminated string literal because python wants code to be ended in the same line as we have used single quotes.
'''


Friend = '''He said,
Hi Sindhu
How are you
"I want to eat an apple." '''
print(Friend)       #output = He said,
                            # Hi Sindhu
                            # How are you
                            # "I want to eat an apple." 
#For strings to be used in multiple lines, we have to use either triple single quotes or triple double quotes.


'''
Accessing Characters in a String:
In Python, string is like an array(collection of items) of characters.
We can access the parts of a string by using index which starts from 0.
Square brackets can be used to access the elements of a string.
'''

name = "Sindhu"

print(name[0])      #output = S
print(name[1])      #output = i
print(name[2])      #output = n
print(name[3])      #output = d
print(name[4])      #output = h
print(name[5])      #output = u

#print(name[6])      #output = index error

#In the above line, there was not any index numbered 6 that we wanted to print.


'''
Looping through the String:
To access the parts of a string , we use loop character also.
'''

print("Lets use a for loop\n")
for character in name:
    print(character)    
#output =  S
        #  i
        #  n
        #  d
        #  h
        #  u

    

Comments

Popular posts from this blog

Print Function

Arithmetic Operators

Sets in Python