03 strings
title: Python Strings author: Juma Shafara date: "2023-11" date-modified: "2024-11-25" description: What are strings and how do we use them in Python? keywords: [python, python programming, python variables, strings]¶

Strings¶
Strings are simply text. A string must be surrounded by single or double quotes
In this notebook, you will learn the following about strings
Table of Contents¶
- How to create strings
- String methods
- Exercise
House to create strings¶
We can create a string by writing any text and we enclose it in quotes. An example is as below
# Strings
name = 'Juma'
other_name = "Masaba Calvin"
statement = 'I love coding'
Single or double quotes?¶
Use single quotes when your string contains double quotes, or the vice versa.
# when to use which quotes
report = 'He said, "I will not go home"'
text = 'shafara loves coding'
capitalized_text = text.capitalize()
print(capitalized_text)
Shafara loves coding
Convert to Upper Case¶
The upper() function returns a copy of the given string but all the letters are in upper case.
Note that this does not modify the original string.
text = 'JavaScript'
upper_text = text.upper()
print(upper_text)
JAVASCRIPT
Convert to Lower Case¶
The lower() function returns a copy of the given string but all the letter are in lower case.
Note that it does not modify the original text/string
text = 'JavaScript'
lower_text = text.lower()
print(lower_text)
javascript
Get the lenght of a String¶
The length of a string is the number of characters it contains
The len() function returns the length of a string. It takes on paramter, the string.
text = 'JavaScript'
text_length = len(text)
print(text_length)
10
Replace Parts of a String.¶
The replace() method/function replaces the occurrences of a specified substring with another substring.
It doesn't modify the original string.
text = 'shafara is a good girl'
corrected_text = text.replace('shafara', 'viola')
print(corrected_text)
viola is a good girl
Check if a Value is Present in a String¶
To check if a substring is present in a string, use the in keyword.
It returns True if the substring is found, otherwise False.
text = 'shafara loves coding'
print('shafara' not in text)
False
Exercise¶
Write a program to convert a given character from uppercase to lowercase and vice versa.