Python Strings

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

Juma Shafara

Published

November 1, 2023

Modified

November 25, 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

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

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 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.

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

Back to top