String in Python part - 1

Sajjad Rahman - Aug 18 '23 - - Dev Community

In Python, a string is a sequence of characters enclosed within either single ('') or double ("") quotation marks. It's a fundamental data type used to represent textual data. Strings can contain letters, numbers, symbols, and even spaces.

How strings work in Python

Creating Strings

we can create a string by using '' or double quotation marks. for example

myString = "Mlops journey 2023"
country = 'Bangladesh'
name ='sajjad rahman'
Enter fullscreen mode Exit fullscreen mode

Indexing

An index refers to the position of a character within that string. It's a numerical value that helps identify the location of a specific character. Also, we know that index starts from 0 and increases by 1 . For example

myString = "Mlops journey 2023"
myString[0] 
'M' # output 
myString[7]
'j'
Enter fullscreen mode Exit fullscreen mode

Indexing

Each character in a string has a specific index, starting from 0 for the first character. You can access individual characters using their indices. For example, "Python"[0] returns 'P'.

Negative Index: Yes, the negative index is allowed in Python. where -1 corresponds to the last character, -2 to the second-to-last, and so on. For example

myString = "Mlops journey 2023"
myString[-1]
'3' # output
myString[-8]
'n' # output
Enter fullscreen mode Exit fullscreen mode

String Slicing

Slicing allows you to extract a portion of a string. we can specify a start index, an end index (exclusive), and a step size. For example,


myString[3:]
'ps journey 2023'
myString[3:8]
'ps jo'

Enter fullscreen mode Exit fullscreen mode

String Concatenation

We can combine strings using the + operator. For example,


firstName = 'sajjad'
lastName = 'rahman'
fullNmae = firstName + lastName
print(fullName)
'sajjad rahman' # output 
Enter fullscreen mode Exit fullscreen mode

String Length

The len() function returns the number of characters in a string. For example,

len(myString)
18 # output 
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . .
Terabox Video Player