Basic Python Strings
   6 min read


Common functions and methods for strings…

print()

Example:

name = 'Nina'                   #define variable & assign a string value.
address = 'Hollyhock Cottage
print(name,"resides at",address) #print inserts default space in output.

Nina resides at Hollyhock Cottage

Sep parameter in print function

sep = ‘’

Use sep parameter. Use single quotes to specify the separator for the arguments in the output string.

The default is no-space.

Example:

name = 'Nina'      #define variable & assign a string value.
address = 'Hollyhock Cottage
print(name," resides at ",address,".",sep='')  #Sep parameter with no-space overrides space inserted by print. Use spaces in " resides at ".

Nina resides at Hollyhock Cottage.

Sep parameter in print function

Use sep parameter. Use single quotes to specify the separator for the arguments in the output string.

Example:

name = 'Nina'
address = 'Hollyhock Cottage'
state = 'California'
print(name,address,state,sep=',')    #Use sep to insert comma.

Nina,Hollyhock Cottage,California

Format method

string.format()
<string with placeholder(s)>.format(value1, value2)

The format method assigns a numerical index (beginning with 0) to each string value.
Specify string values in the format method.
Specify numerical index (correlating to the required value) in the string's placeholder(s) using curly braces.

Example:

name = 'Nina'
print('Hello {0}'.format(name))
#format method indexes parameter(s) and inserts them in the string's placeholder(s) {}.

Hello Nina

Example:

name = 'Nina'
library = 'Marsh Public Library'
book = 'The Hungry Tide'
print('Hello {0}, {2} is ready for pickup from {1}.'.format(name,library,book))
#format method indexes parameters in numerical order and inserts them in the string's placeholders {}.

Hello Nina, The Hungry Tide is ready for pickup from Marsh Public Library.

F strings

f‘ ’

Insert string values in placeholders using curly braces in f-string.
An alternative to the string format method with simpler syntax (Python 3.6 and above).

Use uppercase F or lowercase f.
Use single or double quotes.

Example:

name = 'Nina'
print(f'Hello {name}')

Hello Nina

Example:

name = 'Nina'
library = 'Marsh Public Library'
book = 'The Hungry Tide'
print(f'Hello {name}, {book} is ready for pickup from {library}.')

Hello Nina, The Hungry Tide is ready for pickup from Marsh Public Library.

String representation of a number with specified decimal places

Example:

tempFahrenheit = float(input("Enter a temperature in Fahrenheit: "))
tempCentigrade = ((tempFahrenheit - 32) *5/9)
print(str(tempCentigrade) + chr(176))     #unrounded number
print(f'{tempCentigrade:.2f}' + chr(176)) #rounded to 2 decimal places.

Enter a temperature in Fahrenheit: 67.2
19.555555555555557°
19.56°

If … Else Statement with String

Example:

name = 'Nina'
library = 'Marsh Public Library'
book = 'The Hungry Tide'
bookStatus = 'Available'
if bookStatus == 'Available':   # do not indent if.
   print(f'Hello {name}, {book} is ready for pickup from {library}.')
   #use indent to define scope.
else:
   print(f'Sorry, {book} is not available yet.')
   #use indent to define scope.

Hello Nina, The Hungry Tide is ready for pickup from Marsh Public Library.

Example:

name = 'Nina'
library = 'Marsh Public Library'
book = 'The Hungry Tide'
bookStatus = 'Not available'
if bookStatus == 'Available':   # do not indent if.
   print(f'Hello {name}, {book} is ready for pickup from {library}.')
   #use indent to define scope.
else:
   print(f'Sorry, {book} is not available yet.')
   #use indent to define scope.

Sorry, The Hungry Tide is not available yet.

Multi-line Strings

Python permits single and double quotes. Use either (if not combining both).

Example:

address = '''Nina Adan   #start with triple quotes to preserve the line structure.
"Confidential"   #double quotes to differentiate from triple quotes.
Hollyhock Cottage,
Oakwood Village,
California'''    #ending triple quotes.
print(address)   

Nina Adan
"Confidential"
Hollyhock Cottage,
Oakwood Village,
California

User Input

input()

Example:

name = input('Enter your name: ')
print('Hello',name)

Enter your name:

Convert String to Lowercase

string.lower()

Example:

print('Visit the Help Page at Myworld.org'.lower())

visit the help page at myworld.org

Convert Non-English String to Lowercase

string.casefold()

Use to convert non-English (Latin script) characters (regardless of encoding) to transliterated English lowercase characters.

Example:

GermanStr = 'ß'
print(GermanStr.casefold())
#convert German character ß to the equivalent English characters ss.

ss

Encode String

string.encode()

Encode a string using specified coding. Default is UTF-8 if not specified.

Example:

>>> 'Château de Montbéliard'.encode("utf-8")
#encode â in 2 bytes (0xc3 and 0xa2), and é in 2 bytes (0xc3 and 0xa9).

b'Ch\xc3\xa2teau de Montb\xc3\xa9liard'

Decode String

string.decode()

Decode characters in a string. Default is UTF-8 if not specified.

Example:

>>> b'Ch\xc3\xa2teau de Montb\xc3\xa9liard'.decode("utf-8")
#decode characters with diacritics.

'Château de Montbéliard'

Check String

Check for phrase or characters using the keyword in
Returns True or False.

Example:

address = 'Nina Adan, Hollyhock Cottage, Oakwood Village, California'
print("California" in address)
#use in to check the string for California.

True

Determine Length of String

len()

Begins with 1.

Example:

>>> len('The Hungry Tide')

15

Use Index to Locate Character

string[ ]

Strings are arrays indexed starting at position 0. Each character has a length of 1.
Specify the index number in square brackets to access the character.
Strings are also indexed from the last character in the string to the start of the string using negative integers. To access the last character in a string use -1. Access the second to last character using -2, etc.
To access a substring, give the start or end index, or specify both. If the end index is specified, the result includes items upto (but excluding) the final index.

Example:

book = 'The Hungry Tide'
print(book[4]) #returns the 4th character.

H

Example:

book = 'The Hungry Tide'
print(book[3]) #returns the 3rd character (blank space).

>>>

Example:

myString = 'elephants'
mySubstring = (myString[-3:]) #returns the last 3 characters.
print(mySubstring)

nts

Find Text

string.find(text, start, end)

Finds the first occurence of the text and returns the index for the first character.

  • Index for the start of the range in which to search is optional (default is 0)
  • Index for the end of the range in which to search is optional (default is the end of the string)
  • Returns -1 if the text is not found.
Example:

book = 'The Lighthouse at The Rock'
print('Contains The at position: ', book.find('The'))
#returns the index for the first occurence of the.

Contains The at position: 0

Find Last Text

string.rfind(text, start, end)

Finds the last occurence of the text and returns the index for the first character.

  • Start index is optional (default is 0)
  • End index is optional (default is the end of the string)
  • Returns -1 if the text is not found.
Example:

book = 'The Lighthouse at The Rock'
print('Contains The at position: ', book.rfind('The'))
#returns the index for the last occurence of the.

Contains The at position: 18

Replace String

string.replace(old,new)

Example:

import datetime

timeStamp = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")

print("The time now is " + timeStamp.replace("PM","pm").replace("AM","am") + ".")
# %p returns AM/PM. Replace PM with pm and AM with am.

The time now is 11:56pm on June 06, 2021.

Remove Trailing Characters

string.rstrip('characters')

Example:

my_string = 'It was a dark and stormy night.'
newString = my_string.rstrip('.')
print(newString)

It was a dark and stormy night

Remove Leading Characters

string.lstrip('characters')

Example:

my_string = 'Part 1. "It was a dark and stormy night".'
newString = my_string.lstrip('Part 1.')
print(newString)

“It was a dark and stormy night”.

Convert Integer to String

str()

Example:

>>> str(114)

'114'