Strings in Python – Slice and Repetition operator

By | October 29, 2019

Strings are the most frequently used data type of any programming language. In python, we can use single quotes or double quotes to declare a String. But generally, we use Single Quotes to declare Strings in Python.

str = 'What is Slice Operator in Python?'
str2 = "What is Repetition Operator?"

How to Declare Multi-Line Strings in Python?

To declare multi-line strings, we use triple quotes. Again, here we can either use Tripple single quotes or double-quotes.

myString = '''Learning Python is Easy.
                       on MyEasyTuts'''

We can also use triple quotes if our existing strings contain double-quotes.

stringWithDoubleQuote = '''We can use "double quotes" inside the string easily.'''

Slice Operator for Python Strings

It is used by Strings and Collection in Python. For Strings, it returns the Substring of the provided range.

Syntax – stringName [beginIndex : endIndex]
=> It will return Sub-String from Begin Index to (End – 1) Index

str = 'Read Python Tuts on MyEasyTuts'
subStr1 = str[1:6]

=> Now subStr1 has the value of “ead P”

=> Here beginIndex is Optional. By Default, python will pickup the first character of the string.
=> endIndex is also Optional. By Default, python will take the end of the String.

subStr2 = str[:]


=> Above statement is perfectly valid. And it will contain the whole string value.

Also Read – Solved Undefined reference to ‘pthread_create’

Types of Index for Python Strings

There are two types of indexes in Python
1) Positive Index
2) Negative Index

Positive Index – It is the normal index that we have used in every programming language.

Negative Index – It provides the flexibility for accessing elements of Python Strings. It starts with -1.
=> If we define the startIndex as -1, it will represent the last element of the String.

slice-operator-python
Python Negative Index
str = 'MyEasyTuts'
str2 = str[-6 : -1]
print(str2)
# syTut

Advance Syntax of Slice Operator in Python

Syntax
stringName [beginIndex : endIndex: step]
# Here step is – the number we want to skip after every iteration. e.g. if the value of step is 2. Then we will access, every 2nd element after the beginIndex till the endIndex.

str = 'MyEasyTuts For Python Lectures'
str2 = str [1 : 10 : 2]
print(str2)
# prints - yayus

Also Read – Guard Statement in Swift 5

Repetition Operator in Python

Syntax
stringName * N
Here N is integer. It is the number of times that we want to repeat the String.

str = "AbC1"
str2 = str * 2
print(str2)
#prints - AbC1AbC1

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.