In this article, we’ll be covering about Strings in Python.
Strings in Python are a sequence of characters enclosed in single-quotes, double-quotes or sometimes in triple-quotes.
string = "Hello World" print(type(string))
Output:
<class 'str'>
Accessing characters in String: We can access characters in the string by using an index number in the square brackets.
string = "Hello World" print(string[0]) print(string[4])
Output:
H o
Iterating through String: We can use both for and while loop to iterate through a string.
string = "Hello World" print("Iterating through string using for loop") # for loop for i in string: print(i) print("Iterating through string using while loop") # while loop j = 0 while j < len(string): print(string[j]) j += 1
Output:
print("Iterating through string using for loop") H e l l o W o r l d print("Iterating through string using while loop") H e l l o W o r l d
Deleting a character: We cannot delete or remove any character from the string as they are immutable. But we can delete the entire string using del keyword/function.
string = "Hello World" del string # del(string), both syntax work print(string)
Output:
Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python36\all_prgm\biochemithon articles\testing bioc.py", line 3, inprint(string) NameError: name 'string' is not defined
Concatenation of two or more Strings: Joining two or more strings into a single string is called concatenation.
We can either use ‘+’ operator or f-string to join strings.
string1 = "Hello" string2 = "World" print("string concatenation using \ '+' operator:\n",string1 + string2) print("string concatenation using \ 'f-string':\n",f'{string1}{string2}')
Output:
string concatenation using '+' operator: HelloWorld string concatenation using 'f-string': HelloWorld
We can also use ‘*’ operator to repeat the string for a given number of times.
string = "Hello" print(string * 5)
Output:
HelloHelloHelloHelloHello
Slicing: It is used to return a part of the string. We need to specify the starting index (optional) and the ending index, separated by a colon.
string = "Hello World" print(string[2 : 6])
Output:
llo
We can also use negative index to slice string from the end.
string = "Hello World" print(string[-5 : -2])
Output:
Wor
Length of String: We can use len() function to find out the length of the string.
string = "Hello World" print(len(string))
Output:
11
String Membership test: To check if a substring exist in the string or not we use ‘in’ keyword.
print("ello" in "Hello World") print("ab" in "Hello World")
Output:
True False