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

Learn Python 3 - Strings Reference Guide - Codecademy

Strings in Python can represent sequences of characters. They can be indexed, sliced, modified, and joined using various string methods. Common string methods include lower(), upper(), strip(), split(), replace(), title(), and join() which allow manipulating the case, formatting, extracting substrings, and concatenating strings. Strings are immutable in Python, so reassigning is needed to change string values.

Uploaded by

Yash Purandare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Learn Python 3 - Strings Reference Guide - Codecademy

Strings in Python can represent sequences of characters. They can be indexed, sliced, modified, and joined using various string methods. Common string methods include lower(), upper(), strip(), split(), replace(), title(), and join() which allow manipulating the case, formatting, extracting substrings, and concatenating strings. Strings are immutable in Python, so reassigning is needed to change string values.

Uploaded by

Yash Purandare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

10/03/2020 Learn Python 3: Strings Reference Guide | Codecademy

Learn Python 3
Strings
Print cheatsheet

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

For instance, to print a string with quotation marks, the given code snippet can
be used.

txt = "She said \"Never let go\"."


print(txt) # She said "Never let go".

The Python in syntax


In Python, the in syntax is used to determine if a letter or a substring exists in
a string. It returns True if a match is found, otherwise False is returned.

game = "Popular Nintendo Game: Mario Kart"


print("l" in game) # Prints True in the console.
print("x" in game) # Prints False in the console.

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 1/7
10/03/2020 Learn Python 3: Strings Reference Guide | Codecademy

Indexing and Slicing Strings


Python strings can be indexed using the same notation as lists, since strings are
lists of characters. A single character can be accessed with bracket notation
( [index] ), or a substring can be accessed using slicing ( [start:end] ).

Indexing with negative numbers counts from the end of the string.

str = 'yellow'
str[1] # => 'e'
str[-1] # => 'w'
str[4:6] # => 'ow'
str[:4] # => 'yell'
str[-3:] # => 'low'

Iterate String
To iterate through a string in Python, “for…in” notation is used.

str = "hello"
for c in str:
print(c)

# h
# e
# l
# l
# o

l̀en()’ Built-in Function in Python


In Python, the built in function len() calculates the length of objects. It can be
used to compute the length of strings, lists, sets, and other countable objects!

length = len("Hello")
print(length)
# output: 5

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 2/7
10/03/2020 Learn Python 3: Strings Reference Guide | Codecademy

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


print(len(colors))
# output: 3
print(len(colors[1]))
# output: 6

String Concatenation
To combine the content of two strings into a single string, Python provides the
+ operator. This process of joining strings is called concatenation.

x = 'One fish, '


y = 'two fish.'
z = x + y
print(z)
# 'One fish, two fish.'

Immutable strings
Strings are immutable in Python. This means that once a string has been
de ned, it can’t be changed.

There are no mutating methods for strings. This is unlike data types like lists,
which can be modi ed once they are created.

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

fruit = "Berry"
indx = fruit[6]

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 3/7
10/03/2020 Learn Python 3: Strings Reference Guide | Codecademy

Python String .format()


The Python string method .format() replaces empty brace ( {} ) placeholders
in the string with its arguments.

If keywords are speci ed within the placeholders, they are replaced with the
corresponding named arguments to the method.

msg1 = 'Fred scored {} out of {} points.'


msg1.format(3, 10)
# => 'Fred scored 3 out of 10 points.'

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


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

Lower
In Python, the string method .lower() returns a string with all uppercase
characters converted into lowercase. .lower() does not take any input
arguments.

greeting = "Welcome To Chili's"


print(greeting.lower())

# welcome to chili's

The .strip() String Method in Python


The string method .strip() can be used to remove characters from the
beginning and end of a string.

A string argument can be passed to the method, specifying the set of


characters to be stripped. With no arguments to the method, whitespace is
removed.

text1 = ' apples and oranges '

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 4/7
10/03/2020 Learn Python 3: Strings Reference Guide | Codecademy

text1.strip() # => 'apples and oranges'

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'

Python string method .title()

The Python string method .title() returns the string in title case. With title
case, the rst character of each word is capitalized while the rest of the
characters are lowercase.

my_var = "dark knight"


print(my_var.title()) # "Dark Knight"

Python string .split() method


The Python string method .split() will split a string into a list of items.

If an argument is passed to the method, that value is used as the delimiter on


which to split the string.

If no argument is passed, the default behavior is to split on whitespace.

text = "Silicon Valley"


print(text.split()) # ['Silicon', 'Valley']
print(text.split('i')) # ['S', 'l', 'con Valley']
print(text.split('l')) # ['Si', 'icon Va', '', 'ey']

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 5/7
10/03/2020 Learn Python 3: Strings Reference Guide | Codecademy

Python string method .find()

The Python string method .find() returns the index of the rst occurrence of
the string passed as the argument. It returns -1 if no occurrence is found.

mountain_name = "Mount Kilimanjaro"


print(mountain_name.find("o")) # Prints 1 in the console.

String replace
The .replace() method is used to replace the occurence of the rst argument
with the second argument within the string.

The rst argument is the old substring to be replaced, and the second argument
is the new substring that will replace every occurence of the rst one within the
string.

fruit = "Strawberry"
print(fruit.replace('r', 'R'))

# StRawbeRRy

Python string method .upper()

The Python string method .upper() returns the string with all lowercase
characters converted to uppercase.

dinosaur = "T-Rex"
print(dinosaur.upper())
# Prints T-REX in the console.

The .join() String Method in Python


In Python, the .join() method can be used to concatenate a list of strings
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet 6/7
10/03/2020 Learn Python 3: Strings Reference Guide | Codecademy

together to create a new string joined with the desired delimiter.

The .join() method is run on the delimiter and the array of strings to be
concatenated together is passed in as an argument.

# An example of a .join()
x = "-".join(["Codecademy", "is", "awesome"])

# prints "Codecademy-is-awesome"
print(x)

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

You might also like