Python Strings

Python String is usually sequence of characters. In Python we use ” (double quotes) or ‘ (single quotes) to represent a string. In this article, we will see how to create, access, use and manipulate strings in Python programming language.

How to create Python string:
There are several ways to create strings in Python.
1. We can use ‘ (single quotes)
2. We can use ” (double quotes)
3. Triple double quotes “”” or triple single quotes ”’ are used for creating multi-line strings in Python.

1. Create string using single quote:

mystr1='Welcome to r2schools' mystr2="welcome to r2schools" mystr3='''Welcome to r2schools website and r2schools youtube channel'''

Python Strings

2. How to access Python string
A string is nothing but an array of characters so we can use the indexes to access the characters of a it. Just like arrays, the indexes start from 0 to the length-1.

Examples:

str1='Welcome to r2schools' #display first character of string str1 print(str1[0]) #display last character of a string print(str1[-1]) #display last but one character of string. print(str1[-2])

3.1 Python string operations
1. Python String Sliciing
We can slice a Python string to get a substring out of it. To understand the concept of slicing we must understand the positive and negative indexes in Python. Lets take a look at the few examples of slicing.

str1="r2schools python" # displaying whole string print("The original string is: ", str1) # slicing 10th to the last character print("str1[9:]: ", str1[9:]) # slicing 3rd to 6th character print("str[2:6]: ", str1[2:6]) # slicing from start to the 9th character print("str[:9]: ", str1[:9]) # slicing from 10th to second last character print("str[9:-1]: ", str1[9:-1])

3.2. Python String Repetition:

Using * operator to repeat a Python string by specified number of times.

str1="r2schools"

3.3. Python String Concatenation:

The + operator is used to concatenate strings. if you try to use this between string and number then it will throw TypeError.

str1="Welcome to " str2="r2schools" print(str1+str2)

3.4 Python Membership Operators in Strings
in: This checks whether a string is present in another string or not. It returns true if the entire string is found else it returns false.
not in: It works just opposite to what “in” operator does. It returns true if the string is not found in the specified string else it returns false.

str = "Welcome to r2schools.com" str2 = "Welcome" str3 = "David" str4 = "XYZ" # str2 is in str? True print(str2 in str) # str3 is in str? False print(str3 in str) # str4 not in str? True print(str4 not in str))