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.

i.e.

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

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

Example:-

string = "Hello World"
print(string)

Multiline Strings

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

Example :-

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

print(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]

Example:-

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.

Example:-

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

 


String Length

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

Example:-

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

a = "Hello,World!"
print(len(a)) 

 

0 comments
Leave a comment