Strings in Python

Collections of text in Python are called strings. Strings are one of the fundamental Python data types. Python has a built-in string class named str. It is an immutable data type. Anything inside quotes is considered a string in Python, and you can use single or double quotes around your strings like this: 

“This is a string.”

‘This is also a string.’

N = “0123456789″

You can store any sequence of characters inside a string object: your name, your phone number, your address, including the new lines, and so on.

“House # 105, Kamran Block, Iqbal Town, Lahore.”

String Representation:

To represent a string, you wrap it in quotes. There can be multiple ways of doing this:

  • Single quote example: 
  • ‘Single quotes allow you to embed “double” quotes in your string.’
  • ‘95c’
  • ‘My name is “Anas.” ’
  • Double quote example: 
  • “Double quotes allow you to embed ‘single’ quotes in your string.”
  • “What’s up?”
  • “How’s it going?”
  • Triple quote example: 
  • “””Triple quotes using double quotes”””, ‘’’Triple quotes using single quotes‘’’
  • “””Triple quotes allow you to embed “double quotes” as well as ‘single quotes’ in your string. And can also span across multiple lines.”””
  • ‘’’This is a triple quoted string using “single” quotes. ‘’’
  • “””He said, “What’s time is it?” ”””

Strings are Immutable:

Strings are immutable which means if you try to change any value in a string, it will throw an error. You must create a new string in order to incorporate the changes.

E.g.

message = ‘Anas Shafiq’

message[0] = ‘H’

print(message)

Output: TypeError: ‘str’ object does not support item assignment.

String Concatenation:

String concatenation means adding strings together.

Use the + character to add a variable to another variable:

  • x = “Python is”

y = “awesome”

z =  x + y

print(z)

Result: Python isawesome

To add a space between them, add a “ “. You must add space between “ “:

  • a = “Islamabad is the”

b = “capital of Pakistan.”

c = a + “ “ + b

print(c)

Result: Islamabad is the capital of Pakistan.

  • s1 = ‘Apple’

s2 = “Banana”

s3 = ‘Orange’

s4 = s1 + “ “ +  s2 + “ “ + s3

print(s4)

Result:  Apple Banana Orange

If you try to combine a string and a number, Python will give you an error:

  • x = 10

y = “Abdullah”

print(x + y)

Result: TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

String Indexing:

Each character in a string has a numerical position known as an index. Counting in computer science begins at 0. The below example shows a string object whose value is “Python Programming!” Each character is located at an index. The first character in a string is always at index 0. For the string “Python Programming!”, the last character is at index 18. You can also count backward. The last character in any string is always at index -1 when you’re counting backward. For the string “Python Programming!”, the first character, P, is at index -19. Notice that the space is also a character. Accessing an index out of the range will cause an IndexError.

P y t h o n P r o g r a m m i n g !
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
-19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

You can access characters in a string using square brackets [ ] with an integer index.

If you assign the string to a variable, like name = “Python Programming!” you can access it more concisely. 

E.g. name[5] returns ‘n’

name[10] returns ‘g’

name[-18] returns ‘y’

name[-1] returns ‘!’

String Slicing:

Access a range of characters in a string by using the slicing operator colon: 

Specify the start index and the end index, separated by a colon, to return a part of the string. [::]

To slice a string, you can put up to three integers, separated by colons, in square brackets: [start_index : stop_index : step]  

For example,

  • name = ‘Python Programming’

Access characters from 1st index to 3rd index

print(name[1:4])

Result: “yth”

  • name = “Python Programming”

Access characters from 7th index to 17th index

print(name[7:18])

Result: “Programming”

  • name = “Python Programming”

Access characters from 0 index to 10th index

print(name[0:9])

Result: “Python Pr”

  • z = “Usman, Tahir!”

Access characters from 0 index to 9th index

print(z[:8])

Result: “Usman, T”

By leaving out the start index, the range will start at the first character.

  • y = “Usman, Tahir!”

Access characters from 0 index to 9th index

print(y[4:])

Result: “n, Tahir”

By leaving out the end index, the range will go to the end.

Note: If we try to access an index out of the range or use numbers other than an integer, we will get errors.

Negative Indexing:

Use negative indexes to start the slice from the end of the string:

  • b = “Hello, World!”

Access last 5 characters

print(b[-5:])

Result: “orld!”

Visited 12 times, 1 visit(s) today