Introduction to Strings in Python

A string is a sequence of characters enclosed in quotes.

Python provides a variety of methods that we can use to manipulate strings.

# Example of strings
single_quote_str = 'Hello, World!'
triple_quote_str = '''This is a multi-line string.
It can span multiple lines.'''

print(single_quote_str)
print(triple_quote_str)
Hello, World!
This is a multi-line string.
It can span multiple lines.
# 1. upper() - Converts all characters in the string to uppercase.
print(single_quote_str.upper())
HELLO, WORLD!
# 2. lower() - Converts all characters in the string to lowercase.
print(single_quote_str.lower())
hello, world!
# 3. capitalize() - Capitalizes the first character of the string.
print(single_quote_str.capitalize())
Hello, world!
# 4. replace() - Replaces a substring with another substring.
print(single_quote_str.replace("Hello", "Hooray"))
Hooray, World!
# 5. split() - Splits the string into a list of substrings based on a delimiter.
print(single_quote_str.split(','))
['Hello', ' World!']
# 6. join() - Joins a list of strings into a single string with a specified delimiter.
words = ['Python', 'is', 'fun']
print(' '.join(words))
Python is fun
# 7. isnumeric() - Checks if all the characters in the string are numeric (0-9).
# It returns True if all characters are numeric, otherwise it returns False.

numeric_str = "12345"
non_numeric_str = "123abc"

print(numeric_str.isnumeric())  # True
print(non_numeric_str.isnumeric())  # False
True
False

Functions for Strings


Python provides a variety of functions that we can use to manipulate strings. Functions are reusable blocks of code that perform a specific task and can be called with different inputs to get different outputs.

coolString = "Python is cool"

# 1. len() - Returns the length of the string.
print(len(coolString))
14
# 2. str() - Converts a value to a string.
num = 123
print(str(num))
123
# 3. f-strings - Formats strings using placeholders inside curly braces.
name = "Aaditya"
age = 132
print(f"My name is {name} and I am {age} years old.")
My name is Aaditya and I am 132 years old.
coolString = "Python is cool"

# 4. find() - Returns the lowest index of the substring if it is found in the string.
substring = "cool"
print(coolString.find(substring))  # Output: 7
10

Which of the following is a valid way to define a string in Python?

string1 = 'Hello'
string1 = Hello
string1 = Hello'

What does the .upper() method do?

Converts all characters to lowercase
Converts all characters to uppercase
Capitalizes the first letter only

Given string1 = "Hello, World!", what is the output of string1.lower()?

HELLO, WORLD!
hello, world!
Hello, World!