CSDT BLOG

DISCOVER COLLECTIONS AND BLOGS THAT MATCH YOUR INTERESTS.




Share ⇓




What is string in python programming Language?

Bookmark

What is string in python programming Language?

A string in python is a sequence of characters. A character is simply a symbol. For example, the English language has 26 characters.


Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s.


This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encodings used.


strings in Python 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.



We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −

var1 = 'Hello World!'

var2 = "Python Programming"

print(var1)

print(var2)



How to create a string in Python?

Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings.


my_string = 'Hello'

print(my_string)


How to access characters in a string?

We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError. The index must be an integer. We can't use floats or other types, this will result into TypeError.


Python allows negative indexing for its sequences.


The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a string by using the slicing operator :(colon).


#Accessing string characters in Python

str = ‘CSD’TITSolution’

print('str = ', str)


#first character

print('str[0] = ', str[0])


#last character

print('str[-1] = ', str[-1])


#slicing 2nd to 5th character

print('str[1:5] = ', str[1:5])


#slicing 6th to 2nd last character

print('str[5:-2] = ', str[5:-2])


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


0

Our Recent Coment