Loading...
Loading...
00:00:00

Strings And It's Manipulations

Everything written inside double quotes or single quotes called string literal in python. string belongs to <class str>. In python "hello World or 'hello World' both are same. if we write a single character inside single quotes it will be str class type. we can use string as Comments in python.

In Python 3, a string is a sequence of characters enclosed in quotation marks, either single quotes (') or double quotes ("). You can use either type of quotation marks to define a string, but you must use the same type of quotation marks to close the string. Here are some examples:

# Define a string using single quotes
string1 = 'Hello, World!'

# Define a string using double quotes
string2 = "Hello, World!"

Strings in Python 3 are immutable, which means that you cannot change the individual characters in a string once it has been created. However, you can create a new string that is a modified version of an existing string.

Here are some common string operations in Python 3:

# Concatenate two strings
string3 = string1 + string2

# Repeat a string n times
string4 = string1 * 3

# Get the length of a string
length = len(string1)

# Access individual characters in a string
first_char = string1[0]
last_char = string1[-1]

# Slicing a string
substring = string1[0:5]

Strings also support many useful methods, such as lower() and upper() for converting the case of the string, strip() for removing leading and trailing whitespaces, and replace() for replacing a substring with another string.

String Is As Array In Python

In python, there is no array but string can be use as array and we can iterate the whole string using their index. index starts with zero.

str_ = "python programming"
print(str_[0])    # p is at zero index 

String To List

we can type cast the string to the list, all single characters will be item in list.

str_ = "python programming"
lst = list(str_)   # type cast
print(lst)   
#output ['p', 'y', 't', 'h', 'o', 'n', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']

Strings To Tuples

Similarly as list , we can type cast the string into the tuple.

str_ = "python programming"
tple = tuple(str_)  # type cast
print(tple)   
#output ('p', 'y', 't', 'h', 'o', 'n', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g')

Strings Iterations And Check Substring In String

Checking substring in string

str_ = "python programming"
if "pro" in str_:        # return True
    print("yes, present")