Python Strings

What are strings and how do we use them in Python?
Author

Juma Shafara

Published

November 1, 2023

Modified

September 5, 2024

Keywords

python, python programming, python variables, strings

Photo by DATAIDEA

Strings

Strings are simply text. A string must be surrounded by single or double quotes

# 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"'

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.

text = 'shafara VEe'
capitalized_text = text.capitalize()
print(capitalized_text)
Shafara vee

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 = 'shafara VEe'
upper_text = text.upper()
print(upper_text)
SHAFARA VEE

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 = 'shafara VEe'
lower_text = text.lower()
print(lower_text)
shafara vee

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 = 'shafara VEe'
text_length = len(text)
print(text_length)
11

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 VEe'
corrected_text = text.replace('VEe', 'Viola')
print(corrected_text)
shafara Viola

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 VEe'
print('shafara' not in text)
False

What’s on your mind? Put it in the comments!

Back to top