DEV Community

Sajjad Rahman
Sajjad Rahman

Posted on

String in Python part - 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay