USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Strings

Lesson 9/15 | Study Time: 25 Min

Strings in Python



A string in Python is a sequence of characters used to represent text. Strings are immutable, which means their content cannot be changed after creation. They can contain letters, numbers, symbols, and whitespace. Strings are enclosed in single, double, or triple quotes. They support multiline text when triple quotes are used. Strings allow the use of escape sequences for special characters. They are iterable, so each character can be accessed individually. Strings are commonly used for storing and processing textual data. They are essential for input/output operations, file handling, and communication. Strings are a core data type in Python, forming the foundation for text manipulation and representation.

String Methods


A string is an ordered sequence of characters enclosed in single quotes, double quotes, or triple quotes. Python strings are immutable, meaning once a string is created, its characters cannot be changed directly. Python provides many built-in string methods to manipulate, analyze, transform, and search within text. These methods return new strings or values without modifying the original string.




1. Upper()


The upper() method in Python converts all lowercase characters in a string to uppercase. It does not affect digits, symbols, or letters that are already uppercase. This method is commonly used to normalize text, perform case-insensitive comparisons, and ensure consistent formatting in applications like login systems and data cleaning. Since strings are immutable, upper() returns a new string without modifying the original. Understanding upper() helps in handling and standardizing text efficiently.


Syntax:
string.upper()


Example:

text = "hello world"

print(text.upper())      # Converts entire string to uppercase


Output:
HELLO WORLD


2. Lower()


The lower() method in Python converts all uppercase characters in a string to lowercase. It is mainly used for case-insensitive comparisons, such as usernames, email addresses, commands, and search queries. This method is also useful for cleaning text data and ensuring consistency. Since strings are immutable, lower() returns a new string without modifying the original. Understanding lower() helps in standardizing and processing text effectively.


Syntax:
string.lower()


Example:

text = "Python PROGRAMMING"

print(text.lower())


Output:
python programming


3. Title()


The title() method in Python converts the first character of every word in a string to uppercase and the remaining characters to lowercase. It is commonly used for formatting headings, names, titles, book names, sentences, and UI labels. This method ensures a consistent and professional appearance for multi-word text. Since strings are immutable, title() returns a new string without altering the original. Understanding title() helps in standardizing text formatting efficiently.


Syntax:
string.title()


Example:

name = "welcome to python"

print(name.title())


Output:
Welcome To Python


4. Capitalize()


The capitalize() method in Python converts the first character of a string to uppercase and all other characters to lowercase. It is useful for formatting single-sentence text, ensuring grammatically correct outputs, and standardizing user input such as names or the first word of a paragraph. Since strings are immutable, capitalize() returns a new string without modifying the original. Understanding capitalize() helps in maintaining consistent and proper text formatting.


Syntax:
string.capitalize()


Example:

text = "pYtHoN is FUN"

print(text.capitalize())


Output:
Python is fun


5. Strip()


The strip() method in Python removes unwanted characters, usually spaces, from both the beginning and end of a string. It is useful for cleaning user inputs, correcting accidental spaces in forms, and fixing inconsistent text data from files. You can also use it to trim specific characters like commas, brackets, or symbols from the edges. The method does not remove characters from the middle of the string. Understanding strip() helps in preparing clean and consistent text for processing.


Syntax:
string.strip()
string.strip(chars)


Example:

msg = "   Hello Python   "

print(msg.strip())


tag = "<<Python>>"

print(tag.strip("<>"))


Output:

Hello Python

Python


6. Replace()


The replace() method in Python searches for a specific substring within a string and replaces every occurrence with another substring. It is useful for correcting mistakes, modifying words, filtering content, replacing keywords, and cleaning text. Since strings are immutable, replace() returns a new string with the changes while leaving the original string unchanged. Understanding replace() helps in efficiently updating and managing text data.


Syntax:
string.replace(old, new)
string.replace(old, new, count)


Example:

text = "I love Java"

print(text.replace("Java", "Python"))


Output:
I love Python


7. Find()


The find() method in Python searches a string for a specific substring and returns the index where the substring first appears. If the substring is not found, it returns -1 instead of raising an error. This method is useful for locating words, symbols, or patterns in text, such as finding an email domain, a file extension, or checking the presence of a word in a sentence.


Syntax:
string.find(substring)


Example:

text = "learning python"

print(text.find("python"))


Output:
9


8. Count()


The count() method in Python counts the number of times a specified substring appears within a string. It is commonly used in text analysis, word frequency calculation, pattern recognition, and examining datasets like log files or reports. The method is case-sensitive, so uppercase and lowercase letters are counted separately. Understanding count() helps in analyzing and processing textual data efficiently.


Syntax:
string.count(substring)


Example:

data = "banana"

print(data.count("a"))


Output:
3


9. Split()


The split() method in Python breaks a string into smaller parts and stores them in a list. The splitting is done based on a specified delimiter, with the default being whitespace. This method is widely used in data analysis, CSV parsing, tokenizing sentences, separating values, and processing multi-item user input. Understanding split() helps in efficiently managing and manipulating textual data.

Syntax:

string.split()
string.split(delimiter)


Example:

line = "Python is easy"

print(line.split())


Output:
['Python', 'is', 'easy']


10. Join()


The join() method in Python combines all elements of an iterable, such as a list or tuple, into a single string using a specified separator. It is the opposite of split() and is commonly used to reconstruct sentences, generate formatted output, create CSV-style strings, and merge multiple words or characters into one readable string. Understanding join() helps in efficiently building and formatting text from collections.

Syntax:
separator.join(iterable)


Example:

words = ["Python", "is", "fun"]

print(" ".join(words))


Output:
Python is fun


11. Startswith()


The startswith() method in Python checks whether a string begins with a specified substring. It returns True if the substring is found at the start, otherwise False. This method is useful for filtering filenames, validating input formats, checking URLs, and verifying prefixes such as country codes or keywords. Understanding startswith() helps in efficiently analyzing and validating text data.


Syntax:
string.startswith(value)


Example:

msg = "Hello Python"

print(msg.startswith("Hello"))


12. Endswith()


The endswith() method in Python checks whether a string ends with a specified substring. It returns True if the string matches the substring at the end, otherwise False. This method is commonly used for identifying file types (like .jpg, .png, .pdf), checking URL endings, validating user input, and verifying suffixes. Understanding endswith() helps in efficiently analyzing and validating text data.

Syntax:
string.endswith(value)


Example:

msg = "hello.jpg"

print(msg.endswith(".jpg"))


13. Isnumeric() / Isalpha() / Isalnum()


Validation methods in Python are used to check the type of characters present in a string. isnumeric() returns True if every character is a numeric digit and is used to validate numbers in forms, OTP inputs, roll numbers, and quantities. isalpha() returns True if the string contains only alphabetic characters, making it useful for validating names and words. isalnum() returns True if the string contains only letters and numbers, which is helpful for validating usernames, IDs, passwords, and codes. Understanding these methods helps ensure accurate and clean input data.

Syntax:
string.isnumeric()
string.isalpha()
string.isalnum()


Example:

print("123".isnumeric())    

print("Python".isalpha())   

print("py123".isalnum())