Strings#

word = "bonjour"
print(word, len(word))
bonjour 7

Add a . to the variable and then press <TAB> to get all attached methods available.

word.capitalize()
'Bonjour'

After choosing your method, press shift+<TAB> to get interface.

word.upper()
'BONJOUR'
help(word.replace) # or word.replace? 
Help on built-in function replace:

replace(old, new, count=-1, /) method of builtins.str instance
    Return a copy with all occurrences of substring old replaced by new.
    
      count
        Maximum number of occurrences to replace.
        -1 (the default value) means replace all occurrences.
    
    If the optional argument count is given, only the first count occurrences are
    replaced.
word.replace('o','O',1)
'bOnjour'

Strings and print Function#

Strings can be enclosed in single quotes (’…’) or double quotes (”…”) with the same result. \ can be used to escape quotes:

print('spam eggs')          # single quotes
print('doesn\'t')           # use \' to escape the single quote...
print("doesn't")            # ...or use double quotes instead
print('"Yes," he said.')    #
print("\"Yes,\" he said.")
print('"Isn\'t," she said.')
spam eggs
doesn't
doesn't
"Yes," he said.
"Yes," he said.
"Isn't," she said.

print function translates C special characters

s = '\tFirst line.\nSecond line.'  # \n means newline \t inserts tab
print(s)  # with print(), \n produces a new line
print(r'\tFirst line.\nSecond line.')  # note the r before the quote
	First line.
Second line.
\tFirst line.\nSecond line.

String literals with multiple lines#

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""") 
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

\ character removes the initial newline.

Strings can be concatenated (glued together) with the + operator, and repeated with *

3 * ("Re" + 2 * 'n' + 'es ')
'Rennes Rennes Rennes '

Two or more string literals next to each other are automatically concatenated.

text = ('Put several strings within parentheses '
         'to have them joined together.')
text
'Put several strings within parentheses to have them joined together.'

Strings can be indexed, with the first character having index 0. There is no separate character type; a character is simply a string of size one

word = 'Python @ ENSAI'
print(word[0]) # character in position 0
print(word[5]) # character in position 5
P
n

Indices may also be negative numbers, to start counting from the right

print(word[-1])  # last character
print(word[-2])  # second-last character
I
A

Slicing Strings#

  • Omitted first index defaults to zero,

  • Omitted second index defaults to the size of the string being sliced.

  • Step can be set with the third index

print(word[:2])  # character from the beginning to position 2 (excluded)
print(word[4:])  # characters from position 4 (included) to the end
print(word[-2:]) # characters from the second-last (included) to the end
print(word[::-1]) # This is the reversed string!
Py
on @ ENSAI
AI
IASNE @ nohtyP
word[::2]
'Pto  NA'

Python strings cannot be changed — they are immutable. If you need a different string, you should create a new or use Lists.

import sys
try:
    word[0] = 'J'
except:
    print(sys.exc_info()[0])
<class 'TypeError'>
## Some string methods
print(word.startswith('P'))
True
print(*("\n"+w for w in dir(word) if not w.startswith('_')) )
capitalize 
casefold 
center 
count 
encode 
endswith 
expandtabs 
find 
format 
format_map 
index 
isalnum 
isalpha 
isascii 
isdecimal 
isdigit 
isidentifier 
islower 
isnumeric 
isprintable 
isspace 
istitle 
isupper 
join 
ljust 
lower 
lstrip 
maketrans 
partition 
removeprefix 
removesuffix 
replace 
rfind 
rindex 
rjust 
rpartition 
rsplit 
rstrip 
split 
splitlines 
startswith 
strip 
swapcase 
title 
translate 
upper 
zfill

Exercise#

  • Ask user to input a string.

  • Print out the string length.

  • Check if the last character is equal to the first character.

  • Check if this string contains only letters.

  • Check if this string is lower case.

  • Check if this string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward.

# %load solutions/strings/demo.py