In Python, a string is a sequence of any characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).
# Single-quoted string
name = 'DEEPAKRAJTech'
# Double-quoted string
greeting = "Hello, how are you?"
# Triple-quoted string (used for multi-line text)
message = '''This is a
multi-line string
in Python.'''
In Python, the length of a string refers to the number of characters it contains, including letters, numbers, spaces, and special characters.
To find the length of a string, Python provides a built-in function called len()
name = "DEEPAKRAJTech"
print("Length of the string is", len(name))
In Python, each character in a string has a unique index number starting from 0.
You can access any character in a string using square brackets [] with the index number.
text = "Python"
print("First character:", text[0]) # Positive indexing
print("Last character:", text[-1]) # Negative indexingx`
In Python, strings are immutable, which means you cannot change the characters of a string once it is created
text = "Hello"
text[0] = "Y" # โ This will raise an error
# TypeError: 'str' object does not support item assignment
Traversing a string means iterating through each character of the string, one by one. This can be done using a for loop or while loop.
Traversing using while loop
text = "Python"
i = 0
while i < len(text):
print(text[i])
i += 1
Traversing using for loop
text = "Python"
for char in text:
print(char)
String formatting allows you to insert variables or expressions into a string. Python provides several ways to format strings:
1. Using f-strings (Formatted String Literals)
Introduced in Python 3.6, f-strings are the most efficient and modern way to format strings.
name = "Deepak"
age = 25
formatted_string = f"Hello, my name is {name} and I am {age} years old."
print(formatted_string)
2. Using str.format() Method
The str.format() method allows you to insert variables into curly braces { }
# Default Order
formatted_string = "Hello, my name is {} and I am {} years old.".format("Deepak", 25)
print(formatted_string)
# Positional formatting
formatted_string = "Hello, my name is {1} and I am {0} years old.".format(25, "Deepak")
print(formatted_string)
# Keyword formatting
formatted_string = "Hello, my name is {name} and I am {age} years old.".format(age = 25, name = "Deepak")
print(formatted_string)
# Integers formatting
formatted_string = "Binary : {0:b}".format(10)
print(formatted_string)
# Rounding of Integers formatting
formatted_string = "{0:.2f}".format(10 / 3)
print(formatted_string)
# String alignment formatting
text = "{:<10}".format("Python")
print(text, "|")
text = "{:>10}".format("Python")
print(text, "|")
text = "{:^10}".format("Python")
print(text, "|")
Special string operators in Python allow you to perform various operations on strings like concatenation, repetition, slicing, and checking membership.
| Operator | Description | Example | Output |
|---|---|---|---|
| + | Concatenation โ combines two strings | "Hello" + "World" | "HelloWorld" |
| * | Repetition โ repeats the string multiple times | "Hi" * 3 | "HiHiHi" |
| [ ] | Indexing โ accesses a character at a specific index | "Python"[0] | "P" |
| [ : ] | Slicing โ extracts a part of the string | "Python"[1:4] | "yth" |
| in | Membership โ checks if a substring exists in a string | "a" in "apple" | True |
| not in | Non-membership โ checks if a substring does not exist | "z" not in "apple" | True |
| == | Equality comparison โ checks if two strings are equal | "apple" == "apple" | True |
| != | Inequality comparison โ checks if two strings are not equal | "apple" != "banana" | True |
| < | Lexicographical comparison โ checks if one string is smaller than another | "apple" < "banana" | True |
| > | Lexicographical comparison โ checks if one string is greater than another | "apple" > "banana" | False |
| <= | Lexicographical comparison โ checks if one string is smaller or equal to another | "apple" <= "banana" | True |
| >= | Lexicographical comparison โ checks if one string is greater or equal to another | "apple" >= "banana" | False |
It is used to combine two or more strings into a single string. This is known as string concatenation.
first_name = "Deepak"
last_name = "Raj"
full_name = first_name + " " + last_name
print(full_name)
The repetition operator (*) is used to repeat a string multiple times. It multiplies the string by the given Integer number and returns the new string.
x = "Hello " * 3
print(x)
print("==" * 20)
print(" Welcome to Python Class")
print("==" * 20)
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
| Argument | Description | Default Value |
|---|---|---|
| start | The index where the slice starts (inclusive). | 0 (if step is positive), -1 (if step is negative) |
| end | The index where the slice ends (exclusive). | len(S) (if step is positive), -len(S) (if step is negative) |
| step | The interval between indices in the slice. | 1 (default) |
[ : ] Default Values: start = 0, stop = len(string), step = 1
text = "Python"
print(text[:])
[start : ]
text = "Python"
print(text[2:])
[ :stop]
text = "Python"
print(text[:4])
[start:stop]
text = "Python"
print(text[1:4])
[ : :step]
text = "Python"
print(text[::2])
[start:stop:step]
text = "Python"
print(text[1:5:2])
[start : :step]
text = "Python"
print(text[2::2])
[ :stop:step]
text = "Python"
print(text[:4:2])
[start:stop:-1]
text = "Python"
print(text[4:1:-1])
[start:stop: -step]
text = "Python"
print(text[5:1:-2])
[ : : -1]
text = "Python"
print(text[::-1])
Python has a set of built-in methods that you can use on strings.
Note: All string methods return new string. They do not change the original string.
| Method | Description |
|---|---|
| capitalize() | Converts the first character to upper case |
| lower() | Converts a string into lower case |
| upper() | Converts a string into upper case |
| title() | Converts the first character of each word to upper case |
| swapcase() | Swaps cases, lower case becomes upper case and vice versa |
| isalnum() | Returns True if all characters in the string are alphanumeric else return False |
| isalpha() | Returns True if all characters in the string are in the alphabet else return False |
| isdigit() | Returns True if all characters in the string are digits else return False |
| islower() | Returns True if all characters in the string are lower case else return False |
| isupper() | Returns True if all characters in the string are upper case else return False |
| isspace() | Returns True if all characters in the string are whitespaces else return False |
| istitle() | Returns True if the string follows the rules of a title else return False |
| isnumeric() | Returns True if all characters in the string are numeric else return False |
| isdecimal() | Returns True if all characters in the string are decimals else return False |
| isprintable() | Returns True if all characters in the string are printable else return False |
| isidentifier() | Returns True if the string is an identifier else return False |
| endswith() | Returns true if the string ends with the specified value else return False |
| startswith() | Returns true if the string starts with the specified value else return False |
| find() | Searches the string for a specified value and returns the position of where it was found |
| replace() | Returns a string where a specified value is replaced with a specified value |
| count() | Returns the number of times a specified value occurs in a string |
| index() | Searches the string for a specified value and returns the position of where it was found |
| join() | Joins the elements of an iterable to the end of the string |
| split() | Splits the string at the specified separator, and returns a list |
| partition() | Returns a tuple where the string is parted into three parts |
| strip() | Returns a trimmed version of the string |
| lstrip() | Returns a left trim version of the string |
| rstrip() | Returns a right trim version of the string |
| zfill() | Fills the string with a specified number of 0 values at the beginning |
| format() | Formats specified values in a string |
The capitalize() method returns a string where the first character is upper case, and the rest is lower case.
text = "hello world"
print(text.capitalize())
The lower() method returns a string where all characters are lower case. Symbols and Numbers are ignored.
txt = "Hello my FRIENDS"
x = txt.lower()
print(x)
The upper() method returns a string where all characters are in upper case. Symbols and Numbers are ignored.
txt = "Hello my friends"
x = txt.upper()
print(x)
The title() method returns a string where the first character in every word is upper case.
If the word contains a number or a symbol, the first letter after that will be converted to upper case.
txt = "Welcome to my world"
x = txt.title()
print(x)
txt = "Welcome to my 2nd world"
x = txt.title()
print(x)
txt = "hello b2b2b2 and 3g3g3g"
x = txt.title()
print(x)
The swapcase() method returns a string where all the upper case letters are lower case and vice versa.
txt = "Hello My Name Is Raj"
x = txt.swapcase()
print(x)
The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
Example of characters that are not alphanumeric: (space)!#%&? etc.
text1 = "Python123"
text2 = "Python 123"
print(text1.isalnum())
print(text2.isalnum())
The isalpha() method returns True if all characters in the string are alphabets (A-Z or a-z) and the string is not empty. It returns False if the string contains any non-alphabetic characters like digits, spaces, or symbols.
text1 = "Python"
text2 = "Python3"
print(text1.isalpha())
print(text2.isalpha())
The isdigit() method returns True if all the characters in the string are digits (0โ9) and the string is not empty. If the string contains any non-digit character, it returns False.
num1 = "12345"
num2 = "123abc"
print(num1.isdigit())
print(num2.isdigit())
The islower() method returns True if all the alphabetic characters in the string are lowercase. It ignores non-alphabetic characters. If there's at least one uppercase letter, it returns False.
text1 = "hello world"
text2 = "Hello World"
print(text1.islower())
print(text2.islower())
The isupper() method returns True if all the alphabetic characters in the string are uppercase. It ignores digits, spaces, and symbols. If there's at least one lowercase letter, it returns False.
text1 = "HELLO"
text2 = "Hello"
print(text1.isupper())
print(text2.isupper())
The isspace() method returns True if all the characters in the string are whitespace characters (like spaces, tabs \t, or newlines \n). If there is at least one non-whitespace character, it returns False.
text1 = " "
text2 = " Hello "
print(text1.isspace())
print(text2.isspace())
The istitle() method returns True if the string follows the title case rules. In title case, the first character of each word is uppercase, and the remaining characters are lowercase.
text1 = "Python Is Fun"
text2 = "python is Fun"
print(text1.istitle())
print(text2.istitle())
The isnumeric() method returns True if all the characters in the string are numeric characters. This includes digits and numeric characters from other languages or Unicode.
text1 = "12345"
text2 = "12.5"
print(text1.isnumeric())
print(text2.isnumeric())
The isdecimal() method returns True if all characters in the string are decimal characters (0โ9). It does not consider characters like fractions or superscripts as decimal.
text1 = "12345"
text2 = "50.30"
print(text1.isdecimal())
print(text2.isdecimal())
The isprintable() method returns True if all characters in the string are printable, which includes letters, digits, punctuation, and whitespace. It returns False if the string contains any non-printable characters like \n (newline) or \t (tab).
text1 = "Hello, World!"
text2 = "Hello\nWorld"
print(text1.isprintable())
print(text2.isprintable())
The isidentifier() method returns True if the string is a valid identifier in Python (i.e., it follows the rules for variable names).
name1 = "my_var"
name2 = "2nd_var"
print(name1.isidentifier())
print(name2.isidentifier())
The endswith() method checks if the string ends with a specified suffix. It returns True if the string ends with the given suffix, and False otherwise.
text = "Hello, world!"
print(text.endswith("world!"))
print(text.endswith("hello"))
The startswith() method checks if the string starts with a specified prefix. It returns True if the string begins with the given prefix, and False otherwise.
text = "Hello, world!"
print(text.startswith("Hello"))
print(text.startswith("world"))
The find() method searches the string for a specified substring and returns the lowest index where the substring is found. If the substring is not found, it returns -1.
text = "Python is fun"
print(text.find("is"))
print(text.find("Java"))
The replace() method returns a new string in which occurrences of a specified substring are replaced with another substring.
text = "Hello World"
new_text = text.replace("World", "Python")
print(new_text)
The count() method returns the number of times a specified substring appears in the string.
text = "banana"
result = text.count("a")
print(result)
The index() method searches the string for a specified value and returns the position of where it was found. If the substring is not found, it raises a ValueError.
text = "apple"
result = text.index("p")
print(result)
The split() method divides a string into a list based on a specified separator (default is any whitespace).
sentence = "I love Python"
words = sentence.split()
print(words)
The join() method is used to join the elements of an iterable (like a list or tuple) to the end of a string, with the string acting as a separator.
words = ['I', 'love', 'Python']
result = ' '.join(words)
print(result)
The partition() method searches for a specified separator and splits the string into a tuple containing three elements:
(The part before the separator, The separator itself, The part after the separator)
text = "Hello, how are you?"
result = text.partition("how")
print(result)
The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is default).
text = " Hello, Python! "
result = text.strip()
print(result)
text = "xyPythonxy"
result = text.strip("xy")
print(result)
The lstrip() method removes all leading characters (spaces by default) from the left side of the string.
text = " Hello, World! "
result = text.lstrip()
print(result)
text = "xxxPython"
result = text.lstrip("x")
print(result)
The rstrip() method removes all trailing characters (spaces by default) from the right side of the string.
text = " Hello, World! "
result = text.rstrip()
print(result)
text = "helloooooo"
result = text.rstrip("o")
print(result)
The zfill(width) method pads a string with zeros (0) on the left, so that the total length of the string becomes equal to the given width.
text = "42"
result = text.zfill(5)
print(result)
text = "-42"
result = text.zfill(5)
print(result)