Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

CS101_ Introduction to Programming_ Python_ Strings Cheatsheet _ Codecademy

This document provides an overview of various Python string methods, including .format(), .lower(), .strip(), .title(), .split(), .find(), .replace(), .upper(), .join(), and details about string properties such as immutability and indexing. It explains how to manipulate strings, check for substrings, and iterate through characters. Additionally, it highlights the use of escaping characters and the built-in len() function to determine string length.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CS101_ Introduction to Programming_ Python_ Strings Cheatsheet _ Codecademy

This document provides an overview of various Python string methods, including .format(), .lower(), .strip(), .title(), .split(), .find(), .replace(), .upper(), .join(), and details about string properties such as immutability and indexing. It explains how to manipulate strings, check for substrings, and iterate through characters. Additionally, it highlights the use of escaping characters and the built-in len() function to determine string length.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Cheatsheets / CS101: Introduction to Programming

Python: Strings

Python String .format()

The Python string method .format() replaces empty msg1 = 'Fred scored {} out of {} points.'
brace ( {} ) placeholders in the string with its
msg1.format(3, 10)
arguments.
If keywords are specified within the placeholders, they # => 'Fred scored 3 out of 10 points.'
are replaced with the corresponding named arguments
to 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
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 my_var = "dark knight"
case. 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

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 # Prints: ['Silicon', 'Valley']
value 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
print(mountain_name.find("o")) # Prints 1
argument. It returns -1 if no occurrence is found.
in the console.

String replace

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


occurence of the first argument with the second
print(fruit.replace('r', 'R'))
argument within the 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

String Method .join()

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


strings together to create a new string joined with the
"awesome"])
desired delimiter.
The .join() method is run on the delimiter and the
array of strings to be concatenated together is passed print(x)
in as an 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
substring exists in a string. It returns True if a match is
Kart"
found, otherwise False is returned.

print("l" in game) # Prints: True


print("x" in game) # Prints: False

Indexing and Slicing Strings

Python strings can be indexed using the same notation str = 'yellow'
as 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 str = "hello"


is 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

String Concatenation

To combine the content of two strings into a single x = 'One fish, '
string, Python provides the + operator. This process
y = 'two fish.'
of joining 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 fruit = "Berry"


access an index that doesn’t exist, an IndexError is
indx = fruit[6]
generated. For example, the following code would
create an IndexError :
Print Share

You might also like