Lecture8 Strings
Lecture8 Strings
• String Traversal
• String processing refers to the operations performed on strings that allow them
to be accessed, analyzed, and updated.
• Slicing: You can return a range of characters by using the slice syntax.
• Specify the start index and the end index (excluded), separated by a colon, to
return a part of the string.
Strings are Arrays
• Use negative indexes to start the slice from the end of the string:
#Example
#Get the characters from position 5 to position 2 (not Output:
included), starting the count from the end of the string:
orl
b = "Hello,
World!" print(b[-
5:-2])
• String Length: To get the length of a string, use the len() function. This function
returns the length of the string.
Example: Output:
a = "Hello, 13
World!"
String Traversal
• The characters in a string can be easily traversed, without the use of an explicit
index variable, using the for chr in string form of the for statement.
Note: The find, replace, and strip methods in Python can be used to search and
produce modified strings.
String Methods
Python provides a number of methods specific to strings, in addition to the
general sequence operations.
• Checking the Contents of a String
• Searching and Modifying Strings:
• Searching the contents of a String
• Replacing the contents of a String
• Removing the Contents of a String
• Splitting a String
Checking the Contents of a String
Searchi
ng,
Modifyi
ng and
Splittin
g
Strings
String Methods: Examples
• The strip() method: removes any whitespace from the beginning or the
end:
# Deleting a String using of
Example: Output: del
a = " Hello, World! " A =“hello”
print(a.strip()) Hello, World! del a
print(a
)
• The lower() and upper() methods returns the string in lower and upper case
respectively:
Example: Output:
a = "Hello,
World!" hello, world!
print(a.lower()) HELLO, WORLD!
print(a.upper())
String Methods: Examples
• The replace() method replaces a string with another
string:
Example: Output:
a = "Hello, World!"
print(a.replace("H", Jello, World!
"J"))
• The split() method splits the string into substrings if it finds instances of the separator:
Example: Output:
a = "Hello, World!"
print(a.split(",")) ['Hello', ' World!']
Other Check String: Examples
• To check if a certain phrase or character is present in a string, we can use the
keywords in or not in.
Example1:
#Check if the phrase "ain" is present in the following text: Output:
True
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
Example2:
#Check if the phrase "ain" is NOT present in the following text:
Output:
False
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)
String
Concatenation
• To concatenate, or combine, two strings you can use the + operator.
Example 1:
#Merge variable a with variable b into variable c:
Output:
a = "Hello"
HelloWorld
b = "World"
c = a + b
print(c)
Example 2:
#To add a space between them, add a " ": Output:
a = "Hello" Hello
b = "World" World
c = a + " " +
b print(c)
String Format
• We cannot combine strings and numbers.
Output:
Example:
age = 36
txt = "My name is John, I am " +
age print(txt)
Example:
#Use the format() method to insert numbers into strings:
Output:
age = 36
txt = "My name is John, and I am {}" My name is John, and I am
print(txt.format(age)) 36
String Format: Named Indexes
• You can also use named indexes by entering a name inside the curly
brackets {carname}.
• In this case, you must use names when you pass the parameter
values txt.format(carname = "Ford"):
Example:
Output:
I have a Ford, it is a Mustang.
String Format: Example
• The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:
Example: Output:
quantity = I want 3 pieces of item 567 for
3 49.95 dollars.
itemno==49.95
price
567
myorder = "I want {} pieces of item {} for {}
dollars." print(myorder.format(quantity, itemno,
price))
• You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:
Example: Output:
quantity = I want to pay 49.95 dollars
3 for
itemno==49.95
price 3 pieces of item 567
567
myorder = "I want to pay {2} dollars for {0} pieces of item
{1}." print(myorder.format(quantity, itemno, price))
• To insert characters that are illegal in a string, use an
escape character.
• An escape character is a backslash \ followed by the
character you want to insert.
• An example of an illegal character is a double quote inside
a string that is surrounded by double quotes:
Escape Example:
#You will get an error if you use double quotes inside a string
Charact that is surrounded by double quotes:
• The escape character allows you to use double quotes when you
normally would not be allowed:
Example:
\\ Backslash print("This will insert one \\ (backslash).“) This will insert one \ (backslash).
Hello
\n New Line print("Hello\nWorld!“) World!
Hello
\r Carriage Return print("Hello\rWorld!“) World!
\t Tab print("Hello\tWorld!“) Hello World!
\b Backspace print("Hello \bWorld!“) HelloWorld!
#A backslash followed by three integers will result in
\ooo Octal value a octal value: Hello
print("\110\145\154\154\157“)
#A backslash followed by an 'x' and a hex number
\xhh Hex value represents a hex value: print("\x48\x65\x6c\x6c\ Hello
x6f“)
MCQ
1.
s on, while others return a new altered
Some string methods alter the string they are
called
4. Indicate which of the following is true.
a) String method isdigit returns
version of the string. true if the
a) TRUE string applied to contains any digits.
b) FALSE b) String method isdigit returns
true if the string applied to
contains only digits.
2. The find method returns the number of
occurrences of a character or substring within
a given string. 5. Indicate which of the following s.replace('c','e’)
a) TRUE returns for s = 'abcabc’.
b) FALSE a) 'abeabc’ b) 'abeabe’
3. Which of the results below does s[2:4] return 6. Which of the results below does
for the string s = 'abcdef’. s.strip(‘-’)
a) 'cd’ b) 'bcd’ c) 'bc’ d) 'cde' return for the string s = ‘---ERROR---’.
a) '---ERROR’ b) 'ERROR---’ c)
'ERROR'
MCQs:
1.
Answers
Some string methods alter the string they are
called on, while others return a new altered
4. Indicate which of the following is true.
a) String method isdigit returns
version of the string. true if the
a) TRUE string applied to contains any digits.
b) FALSE b) String method isdigit returns true if the
string applied to contains only digits.
2. The find method returns the number of
occurrences of a character or substring within 5. Indicate which of the following s.replace('c','e’)
a given string. returns for s = 'abcabc’.
a) TRUE a) 'abeabc’ b) 'abeabe’
b) FALSE
6. Which of the results below does
3. Which of the results below does s[2:4] return s.strip(‘-’)
for the string s = 'abcdef’. return for the string s = ‘---ERROR---’.
a) 'cd’ b) 'bcd’ c) 'bc’ d) 'cde' a) '---ERROR’ b) 'ERROR---’ c)
'ERROR'