Variables that hold text are of string data type. Strings are sequences of characters. For example, “coder” is a string containing sequence of characters ‘c’, ‘o’, ‘d’,‘ e’ and ‘r’.
We use single quotes or double quotes to represent a string in Python.
my_string = "I am the she coder"
string_1 = 'Hello'
Creating Multiline Strings
To create multiline strings in Python, we use triple double quotes """
or triple single quotes '''
.
multi_string = """
Strings are sequences of characters
We use single quotes or double quotes to represent a string in Python
"""
ms_string = '''
Strings are sequences of characters
We use single quotes or double quotes to represent a string in Python
'''
print(multi_string)
print(ms_string)
Getting The Length Of A String
We use the len() method to know the total number of characters in a string. Remember, even the blank spaces are counted as characters in a string.
my_string = "I am the she coder"
print(len(my_string)) #18
Accessing String Characters
There are three ways to access characters in a string
1. Indexing: In Python indexing of strings starts from 0 till n-1, where n is the size of string. So characters in string of size n, can be accessed from 0 to n-1.
string2 = "hello"
#accessing 1st character in string2
print(string2[0]) # "h"
#accessing 2nd character in string2
print(string2[1]) # "e"
#accessing 4th character in string2
print(string2[4]) # "o"
2. Negative Indexing: We can access characters from the back of a String using negative indexing.
string2 = "hello"
#accessing last character in string2
print(string2[-1]) # "o"
#accessing 2nd last character in string2
print(string2[-2]) # "l"
#accessing 4th last character in string2
print(string2[-4]) # "e"
Note:- Accessing an index out of the range will cause an IndexError. Also, only integers are allowed to be passed as an index, float or other types will cause a TypeError.
string2 = "hello"
print(string2[5]) # IndexError: string index out of range
print(string2[1.5]) # TypeError: string indices must be integers
3. Slicing: Access a range of characters in a string by using the slicing operator colon :
string2 = "hello"
#accessing from 0 character to 2nd character
print(string2[0:3]) # 'hel'
#accessing from 3rd character to last character
print(string2[3:]) # 'lo'
Strings Are Immutable
The characters of a string cannot be changed.
string2 = "hello"
string2[0] = 'j'
print(string2) # TypeError: 'str' object does not support item assignment
Reversing A String
We can Reverse a string by writing [::-1] and the string will be reversed.
string2 = "hello"
print(string2[::-1]) # "olleh"
Joining two strings
We can join (concatenate) two or more strings using the +
operator.
string_1 = "My name is "
string_2 = "Anam"
print(string_1 + string_2) # My name is Anam
print("Hey " + string_2) # Hey Anam
Iterating Through a Python String
We can iterate or go through the characters of a string one by one using a for loop.
string2 = "hello"
for character in string2:
print(character)
Check If A Substring Exists In A String
We can determine whether or not a given element is a component of a specific string using (in) & (not in)
string2 = "hello"
print('e' in 'hello') # True
print('ll' not in 'hello') # False
Escape Sequence
If we want to print a text like She said "Hello"
. We cannot write it by using a single quote or double quote. It will show a syntax error. To avoid error we use escape sequence.
string_1 = "She said \"Hello\" "
print(string_1)
String Formatting (f-Strings)
You can use the format() method of str to insert values into the replacement field {} with positional or keyword arguments
name = 'Grace'
nationality = 'Turkish'
print(f'Her name is {name} and she is {nationality}')
The Str() Constructor
Python has a built-in function str(), which returns a string representation of any object.
x = str(7)
y = str(6.5)
z = str(True)
print(type(x)) # <class 'str'>
print(type(y)) # <class 'str'>
print(type(z)) # <class 'str'>
String Methods
Python has a set of built-in methods that you can use on string objects. Here are few of them:
Upper() – The upper() method returns the string in upper case.
Lower() – The lower() method returns the string in lower case.
Capitalize() – The capitalize() method converts the first character of the string in uppercase and rest of the other characters into lowercase.
Replace() – The replace() method replaces a specified phrase with another specified phrase.
s = "I like Coding!"
print(s.upper()) # I LIKE CODING!
print(s.lower()) # i like coding!
print(s.capitalize()) # I like coding!
print(s.replace("Coding","Writing") # I like Writing!
Here are list of some more string methods :
find() | Searches the string for a specified value and returns the position of where it was found |
count() | Returns the number of times a specified value occurs in a string |
format() | Formats specified values in a string |
index() | Searches the string for a specified value and returns the position of where it was found |
title() | Converts the first character of each word to upper case |
isalnum() | Returns True if all characters in the string are alphanumeric |
isalpha() | Returns True if all characters in the string are in the alphabet |
isascii() | Returns True if all characters in the string are ascii characters |
isdecimal() | Returns True if all characters in the string are decimals |
isdigit() | Returns True if all characters in the string are digits |
islower() | Returns True if all characters in the string are lower case |
isupper() | Returns True if all characters in the string are upper case |
isspace() | Returns True if all characters in the string are whitespaces |
isidentifier() | Returns True if the string is an identifier |