#!/usr/bin/env python # coding: utf-8 # # 2. String # # Get ready to master strings in Python! This section will teach you how to create, manipulate, and work with text data effectively. # # **Strings** are used to store text data in Python. They're considered sequences, meaning Python keeps track of each character in order. This allows us to access specific characters using indexing. Strings are like ordered lists of characters in Python. This means we can refer to individual characters by their position. # # We'll learn about the following topics: # # - [2.1. Creating Strings](#Creating_Strings) # - [2.2. Printing Strings](#Printing_Strings) # - [2.3. Built-in String Functions](#Builtin_String_Functions) # - [2.4. String Indexing](#String_Indexing) # - [2.5. String Properties](#String_Properties) # - [2.6. String Operators](#String_Operators) # - [2.7. Built-in String Methods](#Builtin_String_Methods) # - [2.8. String Formatting](#String_Formatting) #
#
#
Name | #Type in Python | #Description | #Example | #
---|---|---|---|
Strings | #str | #Ordered sequence of characters, using the syntax of either single quotes or double quotes. | #'hello' "Hello" "i don't do that" "2000f" | #
Special Escape Character | #Result | #
---|---|
\n | #New Line | #
\t | #Tab | #
#
#
name_of_string[n-1]
# In[15]:
#Show first element
a[0]
# In[16]:
#Show second element
a[1]
# To get a portion of a string, we can use slicing with the colon `:`.
#
# In general if you want to get everything from nth index to mth index use name_of_string[n:m+1]
# In[17]:
a[2:7]
# In[18]:
#Grab everything past the first term all the way to the length of a which is len(a)
a[1:]
# In[19]:
#Grab every characters up to the 3rd index
a[:3]
# In[20]:
#Grab Everything
a[:]
# In[21]:
a[len(a)-1]
# String indices can also be specified with negative numbers, in which case indexing occurs from the end of the string backward: -1 refers to the last character, -2 the second-to-last character, and so on.
#
#
#
#
# In[22]:
#Last Chatacter (one index behind 0 so it loops back around)
a[-1]
# In[23]:
a[-3]
# In[24]:
a[-len(a)]
# In[25]:
#Grab everything but the last Character
a[:-1]
# In[26]:
a
# In[27]:
print(a[-5:-2])
print(a[20:23])
a[-5:-2] == a[20:23]
# Slicing can also have a third elememnt.
#
# `[start:stop:step]`
#
# - start: numerical index for the slice index
# - stop: index you will go up to but not include
# - step: the size of jump you take
# In[28]:
a[::1]
# In[29]:
#Grab everything, but go in step sizes of 2
a[::2]
# You can specify a negative step value as well, in which case Python steps backward through the string. In that case, the starting/first index should be greater than the ending/second index.
# In[30]:
a[6:0:-2]
# This is a common paradigm for reversing a string.
# In[31]:
a[::-1]
#
#
# ## 2.5. String Properties:
# - **immutability**: Strings in Python are immutable, meaning you can't change individual characters within them once they're created.
# In[32]:
#Let's try to change the first letter to 'c'
a[0] = 'c'
# In truth, there really isn’t much need to modify strings. You can usually easily accomplish what you want by generating a copy of the original string that has the desired change in place. There are very many ways to do this in Python. Here is one possibility:
# In[33]:
'c' + a[1:]
# - **concatenate**: Concatenation refers to the process of joining two or more strings together to form a new, longer string. In Python, you can concatenate strings using the addition operator `+`.
# In[34]:
a + a
# In[35]:
a + ' ' + a
# In[36]:
a + ' New Sentence'
# In[37]:
a[:3] + a[3:]
# In[38]:
a
# The original a string is unchanged until you reassign a.
# - **Reassignment**
# In[39]:
a = a + ' New Sentence!'
# In[40]:
print(a)
# - **Repetition**: In Python, strings support the repetition property, which allows you to create new strings by repeating an existing string multiple times. This is achieved using the multiplication operator `*`.
# In[41]:
a * 2
#
#
# ## 2.6. String Operators:
# - **`in`**: Python also provides a membership operator that can be used with strings. The in operator returns True if the first operand is contained within the second, and False otherwise.
# In[42]:
'W' in a
# In[43]:
'b' in a
# - **`not in`**: The not in operator returns True if the first operand is not contained within the second, and False otherwise.
# In[44]:
'W' not in a
# In[45]:
'b' not in a
# There are also comparison operators which will be discussed later.
#
#
# ## 2.7. Built-in String Methods:
# Objects in Python have built-in functions called methods. These methods are functions inside the object (we will learn about these in much more depth later) that can perform actions or commands on the object itself.
#
# We call methods with a period and then the method name. Methods are in the form:
#
# `object.method(parameters)`
#
# Where parameters are extra arguments we can pass into the method.
#
#
#
# Method
# Description
#
#
#
#
# upper()
# upper case a string
#
#
# lower()
# lower case a string
#
#
# split()
# Split a string by blank space
#
#
# split(m)
# Split a string by the element m (doesn't include the element that was split on)
#
#
# replace(oldvalue,newvalue,count(optional))
# replaces a specified phrase with another specified phrase
#
#
# capitalize()
# first character converted to uppercase and all other characters converted to lowercase
#
#
# swapcase()
# uppercase alphabetic characters converted to lowercase and vice versa
#
#
# title()
# first letter of each word is converted to uppercase and remaining letters are lowercase
#
#
# count(m,a(optional),b(optional))
# number of occurrences of m within the substring indicated by a and b
#
#
# endswith(m,a(optional),b(optional))
# returns True if an string ends with m within the substring indicated by a and b
#
#
# find(m,a(optional),b(optional))
# see if a string contains a m within the substring indicated by a and b and returns the lowest index
#
#
# rfind(m,a(optional),b(optional))
# see if a string contains a m starting at the end within the substring indicated by a and b and returns the lowest index
#
#
# index(m,a(optional),b(optional))
# the index of first occurrence of m for a given substring indicated by a and b
#
#
# rindex(m,a(optional),b(optional))
# the index of first occurrence of m starting at the end for a given substring indicated by a and b
#
#
#
# In[46]:
a
# In[47]:
a.upper()
# In[48]:
a.lower()
# In[49]:
a.split()
# In[50]:
a.split('b')
# In[51]:
a
# In[52]:
a.replace('b','c')
# In[53]:
a.replace('b','c',1)
# In[54]:
a.capitalize()
# In[55]:
a.swapcase()
# In[56]:
a.title()
# In[57]:
a.count('b')
# In[58]:
a
# In[59]:
a.count('b',0,3)
# In[60]:
a.endswith('!')
# In[61]:
a.endswith('!',0,3)
# In[62]:
a.find('Sentence!')
# In[63]:
a.find('b')
# In[64]:
a.rfind('b')
# In[65]:
a.index('b')
# In[66]:
a.rindex('b')
# `.rindex()` is identical to `.rfind()`, except that it raises an exception if m is not found rather than returning -1.
# In[67]:
a.rindex('x')
# In[68]:
a.rfind('x')
#
#
# ## 2.8. String Formatting:
# **`.format()`**: We can use the `.format()` method to add formatted objects to printed string statements.
# In[69]:
'Insert another string with curly brackets: {}'.format('The inserted string')
# **f-string**
# In[70]:
n = 23
m = 25
prod = n * m
print(f'The product of {n} and {m} is {prod}')