0% found this document useful (0 votes)
5 views

Learn Python 3 - Strings Cheatsheet - Codecademy

This document provides a cheatsheet on common string methods and operations in Python. It defines methods like .format(), .lower(), .strip(), and .title() to manipulate string case and contents. It also covers indexing, slicing, escaping characters, and iterating through strings.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Learn Python 3 - Strings Cheatsheet - Codecademy

This document provides a cheatsheet on common string methods and operations in Python. It defines methods like .format(), .lower(), .strip(), and .title() to manipulate string case and contents. It also covers indexing, slicing, escaping characters, and iterating through strings.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

2/3/24, 2:31 PM Learn Python 3: Strings Cheatsheet | Codecademy

Cheatsheets / Learn Python 3

Strings

Python String .format()

The Python string method .format() replaces empty msg1 = 'Fred scored {} out of {} points.'
brace ( {} ) placeholders in the string with its arguments.
msg1.format(3, 10)
If keywords are specified within the placeholders, they
are replaced with the corresponding named arguments to # => 'Fred scored 3 out of 10 points.'
the method.

msg2 = 'Fred {verb} a {adjective} {noun}.'


msg2.format(adjective='fluffy',
verb='tickled', noun='hamster')
# => 'Fred tickled a fluffy hamster.'

String Method .lower()

The string method .lower() returns a string with all greeting = "Welcome To Chili's"
uppercase characters converted into lowercase.

print(greeting.lower())
# Prints: welcome to chili's

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 1/6
2/3/24, 2:31 PM Learn Python 3: Strings Cheatsheet | Codecademy

String Method .strip()

The string method .strip() can be used to remove text1 = ' apples and oranges '
characters from the beginning and end of a string.
text1.strip() # => 'apples and
A string argument can be passed to the method,
specifying the set of characters to be stripped. With no oranges'
arguments to the method, whitespace is removed.

text2 = '...+...lemons and limes...-...'

# Here we strip just the "." characters


text2.strip('.') # => '+...lemons and
limes...-'

# Here we strip both "." and "+"


characters
text2.strip('.+') # => 'lemons and
limes...-'

# Here we strip ".", "+", and "-"


characters
text2.strip('.+-') # => 'lemons and
limes'

String Method .title()

The string method .title() returns the string in title case. my_var = "dark knight"
With title case, the first character of each word is
print(my_var.title())
capitalized while the rest of the characters are lowercase.

# Prints: Dark Knight

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 2/6
2/3/24, 2:31 PM Learn Python 3: Strings Cheatsheet | Codecademy

String Method .split()

The string method .split() splits a string into a list of text = "Silicon Valley"
items:
If no argument is passed, the default behavior is to
split on whitespace. print(text.split())
If an argument is passed to the method, that value # Prints: ['Silicon', 'Valley']
is used as the delimiter on which to split the
string.
print(text.split('i'))
# Prints: ['S', 'l', 'con Valley']

Python string method .find()

The Python string method .find() returns the index of mountain_name = "Mount Kilimanjaro"
the first occurrence of the string passed as the argument.
print(mountain_name.find("o")) # Prints 1
It returns -1 if no occurrence is found.
in the console.

String replace

The .replace() method is used to replace the occurence fruit = "Strawberry"


of the first argument with the second argument within the
print(fruit.replace('r', 'R'))
string.
The first argument is the old substring to be replaced, and
the second argument is the new substring that will # StRawbeRRy
replace every occurence of the first one within the string.

String Method .upper()

The string method .upper() returns the string with all dinosaur = "T-Rex"
lowercase characters converted to uppercase.

print(dinosaur.upper())
# Prints: T-REX

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 3/6
2/3/24, 2:31 PM Learn Python 3: Strings Cheatsheet | Codecademy

String Method .join()

The string method .join() concatenates a list of strings x = "-".join(["Codecademy", "is",


together to create a new string joined with the desired
"awesome"])
delimiter.
The .join() method is run on the delimiter and the array
of strings to be concatenated together is passed in as an print(x)
argument.
# Prints: Codecademy-is-awesome

Strings

In computer science, sequences of characters are


referred to as strings. Strings can be any length and can
include any character such as letters, numbers, symbols,
and whitespace (spaces, tabs, new lines).

Escaping Characters

Backslashes ( \ ) are used to escape characters in a txt = "She said \"Never let go\"."
Python string.
print(txt) # She said "Never let go".
For instance, to print a string with quotation marks, the
given code snippet can be used.

The in Syntax

The in syntax is used to determine if a letter or a game = "Popular Nintendo Game: Mario Kart"
substring exists in a string. It returns True if a match is
found, otherwise False is returned.
print("l" in game) # Prints: True
print("x" in game) # Prints: False

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 4/6
2/3/24, 2:31 PM Learn Python 3: Strings Cheatsheet | Codecademy

Indexing and Slicing Strings

Python strings can be indexed using the same notation as str = 'yellow'
lists, since strings are lists of characters. A single
str[1] # => 'e'
character can be accessed with bracket notation
( [index] ), or a substring can be accessed using slicing str[-1] # => 'w'
( [start:end] ). str[4:6] # => 'ow'
Indexing with negative numbers counts from the end of
str[:4] # => 'yell'
the string.
str[-3:] # => 'low'

Iterate String

To iterate through a string in Python, “for…in” notation is str = "hello"


used.
for c in str:
print(c)

# h
# e
# l
# l
# o

Built-in Function len()

In Python, the built-in len() function can be used to length = len("Hello")


determine the length of an object. It can be used to
print(length)
compute the length of strings, lists, sets, and other
countable objects. # Output: 5

colors = ['red', 'yellow', 'green']


print(len(colors))
# Output: 3

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 5/6
2/3/24, 2:31 PM Learn Python 3: Strings Cheatsheet | Codecademy

String Concatenation

To combine the content of two strings into a single string, x = 'One fish, '
Python provides the + operator. This process of joining
y = 'two fish.'
strings is called concatenation.

z = x + y

print(z)
# Output: One fish, two fish.

Immutable strings

Strings are immutable in Python. This means that once a


string has been defined, it can’t be changed.
There are no mutating methods for strings. This is unlike
data types like lists, which can be modified once they are
created.

IndexError

When indexing into a string in Python, if you try to access fruit = "Berry"
an index that doesn’t exist, an IndexError is generated.
indx = fruit[6]
For example, the following code would create an
IndexError :

Print Share

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 6/6

You might also like