0% found this document useful (0 votes)
9 views1 page

Python Strings Cheat Sheet

The document provides a comprehensive overview of string indexing and slicing in Python, explaining how to access individual characters using both positive and negative indices. It also covers string operators, immutability, and built-in string methods, highlighting how to manipulate and modify strings effectively. Additionally, it includes examples to demonstrate these concepts in practice.

Uploaded by

gihananjulayt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views1 page

Python Strings Cheat Sheet

The document provides a comprehensive overview of string indexing and slicing in Python, explaining how to access individual characters using both positive and negative indices. It also covers string operators, immutability, and built-in string methods, highlighting how to manipulate and modify strings effectively. Additionally, it includes examples to demonstrate these concepts in practice.

Uploaded by

gihananjulayt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python3 For Bioinformatics String Indexing String Slicing with negative

Strings Cheat Sheet In Python, individual items in an ordered set of data can indexing
by: Lana Caldarevic - Youtube: Lantech be accessed directly using a numeric index or key value. Negative indices can
This process is referred to as indexing. be used with slicing as well. -1
refers to the last character, -2 the second-to-last, and so
Strings Individual characters in a string can be accessed by on,howjustto asslicewiththesimple indexing. The diagram below shows
Strings are sequences of character data, wrapped inside specifying the string name followed by a number in substring "oob" from the string "foobar"
single, double, or triple quotes. square brackets ([]). using both positive and negative indices:
'This is a string in Python' # string in single quotes String indexing in Python is zero-based: the first
"This is a string in Python" # string in double quotes character in the string has index 0, the next has index 1,
'''This is a string in Python''' # string in triple quotes and so on. The index of the last character will be the
"""This is a string in Python""" # string in triple double- length of the string minus one.
quotes
String indices can also be specified with negative s[-5:-2]
A string literal can be assigned to a variable, and printed numbers, in which case indexing occurs from the end of >>> "oob"
using print() command the string backward: -1 refers to the last character, -2
the second-to-last character, and so on. s[1:4]
message = "Hello World" >>> "oob"
print(message)
s[-5:-2] == s[1:4]
>>> Hello World >>> True

String Operators s = "foobar" Modifying Strings


Strings are one of the data types Python considers
s[0] immutable, meaning not able to be changed.
Operators + and * can be applied to strings as well. >>> "f"
The + operator concatenates strings and returns new len(s) In truth, there really isn’t much need to modify strings.
string consisting of the operands joined together. >>> 6 You can usually easily accomplish what you want by
generating a copy of the original string that has the
s[len(s)-1] desired change in place.
s = "abc" >>> "r" You can accomplish that by using string indexing or built-
t = "cba" in string method replace().
s+t
>>> "abccba" s = "foobar"
s[-1] s[3] = "x"
>>> "r" >>> TypeError: "str" object does not support item
The * operator creates multiple copies of a string. assignment
If s is a string and n is an integer, either s*n or n*s returns s[-2]
a string consisting of n concatenated copies of s: >>> "a" s = s[:3] + "x" + s[4:]
s
s = "abc" s[-len(s)] >>> "fooxar"
s*3 >>> "f"
>>> "abcabcabc" s = "foobar"
Attempting to index beyond the end of the string results s = s.replace('b', 'x')
in an error: s
>>> "fooxar"
s = "abc" s[6]
3*s >>> IndexError: string index out of range
>>> "abcabcabc" Built-in String Methods
s[-7] Here is a list of only some of methods you can use with
Python also provides a membership, in operator. The in >>> IndexError: string index out of range strings, full list you can find at: https://bit.ly/2YbUjXw
operator returns True if the first operand is contained s = string
within the second, and False otherwise. There is also a not s.capitalize() - converts first character to uppercase
and all other characters to lowercase
in operator, which does the opposite. String Slicing s.lower() - all alphabetic characters converted to
lowercase
Python also allows a form of indexing syntax that
s = "abc" extracts substrings from a string, known as string slicing. s.upper() - all alphabetic characters converted to
s in "I am abc." If s is a string, an expression of the form s[m:n] returns uppercase
>>> True the portion of s starting with position m, and up to but not s.count(<sub>) - returns the number of non-overlapping
including position n. occurrences of substring <sub> in s
s = "abc" s.endswith(<suffix>) - returns True if s ends with the
s not in "I am abc." If we omit the first index, the slice starts at the beginning specified <suffix> and False otherwise
>>> False of the string. Thus, s[:m] and s[0:m] are equivalent. s.find(<sub>) - returns the lowest index in s where
substring <sub> is found
Similarly, if we omit the second index as in s[n:], the slice s.rfind(<sub>) - returns the highest index in s where
extends from the first index until the end. substring <sub> is found
s.startswith(<prefix>) - returns True if s starts with the
Built-in String Functions
Python provides many functions for strings that are built- s = "foobar"
specified <prefix> and False otherwise
s.isalpha() - returns True if s is nonempty and all its
in to the interpreter and always available. s[2:5] characters are alphabetic, and False otherwise
>>> "oba" s.replace(<old>, <new>) - returns a copy of s with all
chr() # Converts an integer to a character s[:5] occurrences of substring <old> replaced by <new>
ord() # Converts a character to an integer >>> "fooba" s.strip([<chars>]) - returns a copy of s with removed
len() # Returns the length of a string s[2:] both leading and trailing <chars>
str() # Returns a string representation of an >>> "obar" s.join(<iterable>) - returns the string that results from
object concatenating the objects in <iterable> separated by s

You might also like