Download as pdf
Download as pdf
You are on page 1of 5
Cheatsheets / Learn Python 3 Strings Strings In computer science, sequences of characters are referred to at strings. Strings can be any length and can include any character such as letters, numbers, symbols, and whitespace (spaces, tas, new lines. Escaping Characters Backslashes ( \ J are used to escape characters in & Python string For instance, to print a string with quotation marks, the given code snippet can be used. The in Syntax ‘The in syntaxis used to determine If aletter or @ substring exists ina string. rreturns true fa match is found, otherwise raise is returned. Indexing and Slicing Strings Python strings can be indexed using the same notation as Tsts, since strings are lists of characters. A single character can be accessed with bracket notation ( tandex] }, oF a substring can be accessed using slicing Ctstartsend} Indexing with negative numbers counts from the end of the string [code]cademy txt = "She said \"Never let go\". ‘txt) # She said "Never let go". game = "Popular Nintendo Game: Mario Kart" "1" in game) # Prints: True in game) # Prints: False "yell" -3:] # => ‘low’ Iterate String To iterate through a string in Python, “for..in’ notation is used. Built-in Function len() In Python, the built-in en¢) function can be used to determine the length of an object. It can be used to compute the length of strings, lists, sets, and other countable objects, 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. 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 s unlike dota types lke ists, which can be modified once they are created [code]cademy “hello” for ¢ in © #h te #1 to length "Hello" length. # output: 5 colors = ['red", 'yellow", ‘green’ colors # Output: 3 x = ‘One fish, y = ‘two fish." # Output: One fish, two fish. IndexError ‘When indexing into a string in Python, if you try to access an index that doesn't exist, an Indexsrron Is generated For example, the following code would eres Python String format) ‘The Python string method format) replaces empty brace ( () ) placeholders in the string with its arguments. It keywords are specified within the placeholders, they are replaced with the corresponding named arguments to the method, String Method . lower() ‘The string method .1oxer() returns a string with all Uppercase characters converted into lowercase. [eodelcadery fruit = "Berry" indx = fruit(6 msgi = ‘Fred scored {} out of {} points.’ nsgl.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." greeting = "Welcome To Chili's greeting. lower # Prints: welcome to chili's String Method .strip() The string method .strin()_ can be used to remove characters from the beginning and end ofa string. ‘string argument can be passed tothe method, specifying the set of characters o be stripped, With no arguments tothe method, whitespace i removed. String Method .title() The string method .:itie() returns the string intitle ‘case. With title case, the first character of each word is ‘capitalized while the rest of the characters ere lowercase. String Method .split() The string method .ss11t() splits string into alist of items: if no arguments passed, the default behevir is to split on whitespace. Ian argument is passed to the method, that value is used as the delimiter on which to split the string. [eodelcadery text1 = ' apples and oranges texti. strip! # => ‘apples and oranges’ text2 = '...+...lemons and limes...-..." characters # Here we strip just the " text2.strip('.") # limes...-' lemons and # Here we strip both "." and" characters text2. strip! limes..." "Lemons and # Here we strip " characters » and text2.strip(’ “lemons and Limes’ my_var = "dark knight" my_var.title # Prints: Dark Knight text = "Silicon Valley" text. split! # Prints: ‘Silicon’, ‘Valley'] text.split(’ # Prints: ['S", ‘L', ‘con Valley'] Python string method .find() The Python string method .rind¢) returns the index of the first occurrence of the string passed as the argument. Itretums -1 if ne occurrence is found, String replace ‘The replace()_ method is used to replace the occurence of the first argument with the second ng ‘The first argument isthe old substring to be replaced, and the second argument is the new substring that will replace every occurence of the fist one within the string argument within the String Method .upper() ‘The string method .wsser() returns the string with all lowercase characters converted to uppercase, String Method . join() The string method join) concatenates alist of strings, 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 fas an argument, [code]cademy mountain_name = "Mount Kilimanjaro” mountain_name.find("o")) # Prints 1 in the console. fruit = "Strawberry" fruit.replace # StRawberRy dinosaur = "T-Rex" dinosaur. upper: # Prints: T-REX x join(["Codecadeny", “is "awesome" # Prints: Codecademy-is-awesome

You might also like