Python String Manipulation Cheat Sheet



Basics

The Ultimate Python Cheat Sheet Keywords Keyword Description Code Examples False, True. String Python Strings are sequences of characters. String Creation Methods: 1. Functions to access all keys and values of the dictionary print( cal'apple '. The return type will be in Boolean value (True or False) word = 'Hello World' word.isalnum #check if all char are alphanumeric word.isalpha #check if all char in the string are alphabetic word.isdigit #test if string contains digits word.istitle #test if string contains title words word.isupper #test if string contains upper case word.islower #test if string contains lower case. Here is my cheat sheet I created along my learning journey. If you have any recommendations (addition. Tagged with python, django, flask, beginners. The Ultimate Python Cheat Sheet Keywords Keyword Description Code Examples False, True Boolean data type False (1 2) True (2 1) and, or, not Logical operators → Both are true → Either is true → Flips Boolean True and True # True True or False # True not False # True break Ends loop prematurely while True: break # finite loop. String Functions (cont) S.upper Returns a string that has all lower characters in string S converted into uppercase characters S.swap ‐ case Returns a string that has all lowercase characters in string S converted into uppercase characters and vice versa S.isup ‐ per Returns True if all alphabets in string S are in upperc ‐ ase.

Print a number print(123)
Print a string print('test')
Adding numbers print(1+2)
Variable assignment number = 123
Print a variable print(number)
Function call x = min(1, 2)
Comment # a comment

Types

Integer 42
String 'a string'
List [1, 2, 3]
Tuple (1, 2, 3)
Boolean True

Useful functions

Write to the screen print('hi')
Calculate lengthlen('test')
Minimum of numbersmin(1, 2)
Maximum of numbersmax(1, 2)
Cast to integerint('123')
Cast to stringstr(123)
Cast to booleanbool(1)
Range of numbersrange(5, 10)

Other syntax

Return a value return 123
Indexing 'test'[0]
Slicing 'test'[1:3]
Continue to next loop iteration continue
Exit the loop break
List append numbers = numbers + [4]
List append (with method call) numbers.append(4)
List item extraction value = numbers[0]
List item assignment numbers[0] = 123

Terminology

syntax the arrangement of letters and symbols in code
program a series of instructions for the computer
print write text to the screen
string a sequence of letters surrounded by quotes
variable a storage space for values
value examples: a string, an integer, a boolean
assignment using = to put a value into a variable
function a machine you put values into and values come out
call (a function) to run the code of the function
argument the input to a function call
parameter the input to a function definition
return value the value that is sent out of a function
conditional an instruction that's only run if a condition holds
loop a way to repeatedly run instructions
list a type of value that holds other values
tuple like a list, but cannot be changed
indexing extracting one element at a certain position
slicing extracting some elements in a row
dictionary a mapping from keys to values

Reminders

  • Strings and lists are indexed starting at 0, not 1
  • Print and return are not the same concept
  • The return keyword is only valid inside functions
  • Strings must be surrounded by quotes
  • You cannot put spaces in variable or function names
  • You cannot add strings and integers without casting
  • Consistent indentation matters
  • Use a colon when writing conditionals, function definitions, and loops
  • Descriptive variable names help you understand your code better

Conditionals

Lists

Defining functions

Loops

Dictionaries

Comparisons

Equals
Not equals !=
Less than <
Less than or equal <=
Greater than >

Useful methods

String to lowercase 'xx'.lower()
String to uppercase 'xx'.upper()
Split string by spaces 'a b c'.split(' ')
Remove whitespace around string ' a string '.strip()
Combine strings into one string ' '.join(['a', 'b'])
String starts with 'xx'.startswith('x')
String ends with 'xx'.endswith('x')
List count [1, 2].count(2)
List remove [1, 2].remove(2)
Dictionary keys {1: 2}.keys()
Dictionary values {1: 2}.values()
Dictionary key/value pairs {1: 2}.items()

Other neat bonus stuff

Zip lists zip([1, 2], ['one', 'two'])
Set my_set = {1, 2, 3}
Set intersection {1, 2} & {2, 3}
Set union {1, 2} | {2, 3}
Index of list element [1, 2, 3].index(2)
Sort a list numbers.sort()
Reverse a list numbers.reverse()
Sum of list sum([1, 2, 3])
Numbering of list elements for i, item in enumerate(items):
Read a file line by line for line in open('file.txt'):
Read file contents contents = open('file.txt').read()
Random number between 1 and 10 import random; x = random.randint(1, 10)
List comprehensions [x+1 for x in numbers]
Check if any condition holds any([True, False])
Check if all conditions hold all([True, False])

Missing something?

Let us know here.

Python is great for string manipulation. Python’s string manipulation ability was definitely one of the reasons for its popularity initially. Python’s built-in methods lets you do most common string manipulations. Here are the String object methods in Python and how to use them.

Python String Manipulation Cheat Sheet

1. How to Check a String Ends With a Suffix?

Python Functions Cheat Sheet

Python String object’s method endswith is great to see if a string/text ends with a specific suffix. It returns True, when the string ends with the suffix, False otherwise.

2. How to Check a String Starts With a Prefix?

Python String object also has a method startswith to see a string/text starts with a specific prefix. It returns True, when the string starts with the prefix, False otherwise.

3. How to Find If A Substring Is in a String?

Often you want to check if a string contains a substring. The best way to do that is use ‘in’ statement in Python.

4. How To Split a String in Python

Often you want to split a text or string using a delimiter and create a list of words in the string. Python’s split() method lets you split a string. By default, split uses consecutive whitespace in the string as a single separator and gets you a list.

You can also specify a delimiter to split method. Here, we split the string with the letter ‘a’ as delimiter.

5. How To Join a List of Strings into a String in Python?

Often one wants to join or concatenate list of strings into a single string. Python’s join() method can be used join strings. While joining we can also specify how we want to join with a delimiter.

6. How To Remove Whitespaces in a String in Python?

Python has three related methods, strip(), lstrip(),rstrip() to remove whitespaces in strings. Let us see examples of using strip(), lstrip(), rstrip() here.

Let us create a text with white spaces in the beginning and in the end.

strip() method removes both the whitespaces, the ones in the beginning and in the end

lstrip() method removes only the left whitespaces and thus leaves the one at the end of the string.

rstrip() method removes only the right whitespaces and thus leaves the one at the beginning of the string.

7. How To Convert to Lower Case?

Python Cheat Sheet Pdf

Python String objects’ lower() method is to convert a string into lower case letters.

8. How To Convert to Upper Case?

Python String objects’ upper() method is for converting a string into upper case. Note all letters in the string will be capitalized.

9. How To Convert to Title Case?

Python’s title() method converts a string to a titlecased version, where the first letter of each word is capitalized, while the characters are lowercase.

Python String Manipulation Cheat Sheet Example

Related posts: