Python – Strings:

In this tutorial, we will work on the Python Strings where we can learn about the manipulation of Strings, using String Operators and string methods and Functions.

First, let us understand that how do we declare the strings in python programming language.

We can declare and print the strings by placing them in single Quotes (‘..’), Double Quotes (“..”), and using the print function too.

Python Strings are Immutable (An Object with a fixed value).

Using the Strings in single quotes (‘…’)

1

2

3

>>>'hello world'

'hello world'

Below command will give an error.

1

2

3

4

5

>>>'let'sstart' # this will give us an error

File ",stdin>, line 1

'let's do it'

^

SyntaxError:invalid syntax

To overcome that we must use escape character \

1

2

>>>'let\'start'

"let's start"

Using the Strings in Double quotes (“…”)

1

2

>>>"let's start"# using double quotes to avoid escape character

"let's start"

Using the Strings in Print() function

1

2

>>>print("let's start")# we have enclose the strings in double quotation inside print funtion

let'sstart

Using the 3 double quotes start and end of the string allows us to print the data including spaces and newlines.

1

2

3

4

5

6

>>>print("""let's

...start

...Now""")

let's

start

now

String Concatenation:

Multiple Strings can be concatenated using (+) symbol. Let us see the example of concatenating the strings.

Example:

1

2

3

4

>>>x="hello"

>>>y="world"

>>>x+y

'helloworld'

String Repetition:

String repetition can be performed by using the (*) symbol. Let us see the example of repetition of strings.

Example:

1

2

>>>3*"hello"

'hellohellohello'

Strings are indexed with each character in a memory location when assigned to a variable. The indexed number starts from zero ‘0’ from first character till the end of the string. Whereas, reverse indexing starts with ‘-1’ from right to left until the starting character. Let us try few examples of retrieving the characters from a word PYTHON in either ways.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

>>x="P Y T H O N"# Word python is written without spaces

012345

-6-5-4-3-2-1

>>x[3]

'H'

>>x[-5]

'Y'

>>x[:4]# Starting from first character, 4th position excluded

'PYTH'

>>x[:-4]# Starting from fourth character from right, 4th position excluded