Python Strings

Vipin | Sun, 14 Jun, 2020 | 160

Strings In Python

String in python are surrounded by either single quotation marks, or double quotation marks.


"Hello" or 'Hello' , both the strings literals

You can display a string literal with the print() function.


string = "Hello World"

Multiline Strings

Multiline Strings in python can be delcared using ''' '''.

Example :-

string = '''
       this is multiline
       String. '''


Note: in the result, the line breaks are inserted at the same position as in the code.

Strings are Array

Like other programming languages in python also strings are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Example :-

string  = "Hello world"

print(string[0]) # H 

String Slicing

In Python String slicing is done using slice operator i.e. [::]

Syntax :-

[start_index : end_index : step]


string  = "Hello World"

string1 = string[0:5]

Negative Indexing

In Python uses negative indexing also to access the string part and slice the string.

Negative indexing start from the last character with index value -1.


a = "SelfCode"
b = a[-5:-1]
print(b) #Code


String Length

To get the length of a string, use the len() function.


The len() function returns the length of a string:

a = "Hello,World!"


Leave a comment