Thursday, April 16, 2015

Python Variable - Strings

Strings can be assigned to variable in either double " " or single quotes ' '. Both will have same output

EX:
str1='This is my first line'
str2="This is my second line"
print(str1)
print(str2)

O/P
This is my first line
This is my second line

Using escape character in the string.

Ex for \n

str1='This is my \n first line'
print(str1)

O/P
This is my
 first line

Raw string:

If you want to display the escape character /n in the string then use r in brfore the string quote

str1=r'This is my \n first line'
print(str1)

O/P
This is my \n first line

Formatting and replacing of variables in string

n=35
str1=r'This is my {}th line'.format(n)
print(str1)

O/P
This is my 35th line 


To display multiple lines without escape character.

For this use single quote or double quote three times

Ex:
str1='''Hi
all. This displays in
many lines.
 Try out'''
print(str1)


O/P
Hi
all. This displays in
many lines.
 Try out

No comments:

Post a Comment