Python Strings

Python strings are an array of characters placed one after the other.

Put string characters in variablePut string characters in variable

name = "Python String"
print(name)

#Python output
Python String

Python string may start from single, double or 3 (”’) single, (“””) double qoutes

a = 'This is a python string...from single qoutes'
b = "This is a python string...from double qoutes"
c = '''This is a python string...from 3 single qoutes on start and finish'''
d = """This is a python string...from 3 double quotes on start and finish"""

print(a)
print(b)
print(c)
print(d)

#Python output
This is a python string...from single quotes
This is a python string...from double quotes
This is a python string...from 3 single quotes on start and finish
This is a python string...from 3 double quotes on start and finish

Strings can also be accessed by index just like arrays.

Example

website_name = "CodeJunker"
print(website_name)
print(website_name[0])
print(website_name[1])
print(website_name[2])
print(website_name[3])
print(website_name[4])
print(website_name[5])
print(website_name[6])
print(website_name[7])
print(website_name[8])
print(website_name[9])

#Python OUTPUT
CodeJunker
C
o
d
e
J
u
n
k
e
r

String `CodeJunker` as 9 characters i.e if we count from 0 their will be 9 characters

print(website_name[10])

#PYTHON ERROR OUTPUT
string index out of range

Escape Special Characters in String

Backslash `\` is used to escape any special character in the string.

Example

string = "This string with double quotes"
e_string = "This string with \"double quotes escaped with a backslash"
a_string = 'I don\'t like this'

print(string)
print(e_string)
print(a_string)

#PYTHON OUTPUT
This string with double quotes
This string with "double quotes escaped with a backslash
I don't like this

Print string in new line use \n

Example

x = 'This will be printed in first line.\nThis will be printed in second line'
print(x)


#PYTHON OUTPUT
This will be printed in first line.
This will be printed in second line

Raw Strings

If for some cases you wanted to omit special character `\` backslash then you can use `raw strings` by placing `r` at start of a string

Example


string = 'Some File Path \temp\name\read'
e_string = r'Some File Path \temp\name\read'
print(string)
print(e_string)

#Python OUTPUT
Some File Path 	emp
ead
Some File Path \temp\name\read 

To Display Multiline message use `”’` or `”””` and use `r` to ommit `\` backslash