# Strings
= 'Juma'
name = "Masaba Calvin"
other_name = 'I love coding' statement
Python Strings
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
Single or double quotes?
Use single quotes when your string contains double quotes, or the vice versa.
# when to use which quotes
= 'He said, "I will not go home"' report
String Methods
In this lesson, we will study some methods(functions) that can be used to work with strings.
Capitalize String
The capitalize()
function returns the string where the first letter is in upper case.
Note that it doesn’t modify the original string.
= 'shafara loves coding'
text = text.capitalize()
capitalized_text 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.
= 'JavaScript'
text = text.upper()
upper_text 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
= 'JavaScript'
text = text.lower()
lower_text 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.
= 'JavaScript'
text = len(text)
text_length 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.
= 'shafara is a good girl'
text = text.replace('shafara', 'viola')
corrected_text 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
.
= 'shafara loves coding'
text print('shafara' not in text)
False
Exercise
Write a program to convert a given character from uppercase to lowercase and vice versa.