Strings: Characters, Substrings, and Manipulation
25 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

An integer is a complex data structure that may be factored into primitive parts.

False (B)

A string's length is the number of characters it contains and can be zero or more.

True (A)

Given the assignment name = "Alan Turing", name[11] would return the last character 'g'.

False (B)

Negative indices in Python strings do not allow access to characters from the end of the string.

<p>False (B)</p> Signup and view all the answers

A count-controlled loop cannot be used to iterate through the characters in a string using the subscript operator.

<p>False (B)</p> Signup and view all the answers

Slicing allows extraction of substrings, and integers are never allowed on either side of colon.

<p>False (B)</p> Signup and view all the answers

With name = "myfile.txt", name[-5:] would correctly extract the last five characters 'file.txt'.

<p>True (A)</p> Signup and view all the answers

The in operator can only be used to check if a target string is at the start of a search string.

<p>False (B)</p> Signup and view all the answers

The in operator returns True if the target substring is not found within the search string, and False otherwise.

<p>False (B)</p> Signup and view all the answers

String methods are called using a function-like syntax, where the string is passed as an argument within parentheses.

<p>False (B)</p> Signup and view all the answers

String methods cannot return any values, but instead modify the original string directly.

<p>False (B)</p> Signup and view all the answers

To view a complete list and documentation of string methods, one can use the list(str) and info(str.method-name) functions.

<p>False (B)</p> Signup and view all the answers

Given 'myfile.txt'.split('.'), the returned list will always include 3 elements.

<p>False (B)</p> Signup and view all the answers

The split method can be used with subscript [-2] to extract the filename's extension.

<p>False (B)</p> Signup and view all the answers

Keyboard input always preferable to input data from a file because it is more secure.

<p>False (B)</p> Signup and view all the answers

Data written or read from a text file requires all number values to be converted to strings.

<p>True (A)</p> Signup and view all the answers

If a file exists when opened in write mode ('w'), Python automatically appends new data to the end of the file.

<p>False (B)</p> Signup and view all the answers

The file.export() method is used to write content to a text file.

<p>False (B)</p> Signup and view all the answers

The open() function only requires the file name as an argument when opening the file. The mode is optional.

<p>False (B)</p> Signup and view all the answers

Upon attempting to open a non-existent file in read mode, Python will automatically create the new file.

<p>False (B)</p> Signup and view all the answers

The method used to read from a file is called filetext().

<p>False (B)</p> Signup and view all the answers

After reaching the end of a file, calling the read() method returns the string "EOF".

<p>False (B)</p> Signup and view all the answers

When reading numbers from a file, the strip() method is essential for removing any leading or following characters before converting the string to an integer or float.

<p>False (B)</p> Signup and view all the answers

The mode rw in the statement open("filename.txt", "rw") opens the file for both reading and writing but not appending.

<p>False (B)</p> Signup and view all the answers

The for loop in Python can iterate through an input file, treating it as a sequence of characters, where each variable is bound to an individual character read from the file.

<p>False (B)</p> Signup and view all the answers

Flashcards

Data Structure?

A collection of smaller pieces of data.

len() function?

A function that returns the number of characters in a string.

Subscript operator?

Accesses characters in a string using their position.

Substring?

A portion of a string.

Signup and view all the flashcards

Slicing?

Obtaining a substring from a string using the subscript operator.

Signup and view all the flashcards

in operator?

Checks if a substring is present in a string.

Signup and view all the flashcards

Method?

Operations that are used with an object.

Signup and view all the flashcards

Text File?

A software object that stores data on a permanent medium.

Signup and view all the flashcards

open(filename, 'w')?

Opens a file for output.

Signup and view all the flashcards

file.write()?

Writes a string to a file.

Signup and view all the flashcards

file.close()?

Closes a file object.

Signup and view all the flashcards

open(filename, 'r')?

Opens a file for reading.

Signup and view all the flashcards

file.read()?

Reads the entire content of a file as a single string.

Signup and view all the flashcards

file.readline()?

Reads a single line from a file.

Signup and view all the flashcards

Study Notes

Objectives

  • Access individual characters in a string
  • Retrieve a substring from a string
  • Search for a substring in a string
  • Use string methods to manipulate strings
  • Open a text file for output and write strings or numbers to the file
  • Open a text file for input and read strings or numbers from the file
  • Use library functions to access and navigate a file system

Accessing Characters and Substrings in Strings

  • You will learn how to extract portions of a string called substrings.
  • This section examines the internal structure of a string.

The Structure of Strings

  • An integer cannot be factored into more primitive parts.
  • A string is a data structure.
  • A data structure consists of smaller pieces of data.
  • A string's length is the number of characters it contains, and it can contain 0 or more characters.
  • The len function returns the string's length, which is the number of characters it contains.
  • len("Hi there!") returns 9.
  • len("") returns 0.

The Subscript Operator

  • The subscript operator is: <a string>[<an integer expression>]
  • Example: Use the subscript operator to examine the first character in the string "Alan Turing"
  • Result: 'A'
  • Example: Use the subscript operator to examine the fourth character in the string Alan Turing
  • Result: 'n'
  • Example: Accessing the length of the name string will cause an error.
  • The last character of a string can be accessed by name[-1]
  • The second to last character can be accessed for example by name[-2]

Subscript Operator Usefulness

  • This operator is useful when you want to use the positions as well as the characters in a string.
  • A count controlled loop can be used alongside this operator.
  • For example, data = "Hi there!" can have its characters printed alongside their index in a loop.

Slicing for Substrings

  • Python's subscript operator can be used to obtain a substring through a process called slicing.
  • Place a colon (:) in the subscript; an integer value can appear on either side of the colon.
  • A string name = myfile.txt can have a substring taken with the subscript operator
  • Returns the entire string for name[0:]
  • 'm' for name[0:1]
  • 'txt' for name[-3:]

Testing for a Substring with the in Operator

  • When used with strings, the left operand of in is a target substring and the right operand is the string to be searched.
  • True is returned if target string is somewhere in search string, or False otherwise.
  • The following code segment traverses a list of filenames and prints just the filenames that have a .txt extension:
fileList = [“myfile.txt”, “myprogram.exe”, “yourfile.txt”]
for fileName in fileList:
    if “.txt” in fileName:
        print(fileName)

String Methods

  • Python includes a set of string operations called methods to make tasks like counting the words in a single sentence easy.
  • Result of len(listOfWords) from a .split() is the number of words in a string.
  • A method behaves like a function, but has a slightly different syntax.
  • A method is always called with a given data value, called an object, as so: <an object>.<method name>(<argument-1>,..., <argument-n>)
  • Methods can expect arguments and return values
  • A method knows about the internal state of the object with which it is called
  • All data values are objects in Python.
  • View a complete list and documentation of string methods by entering dir(str) at a shell prompt
  • Enter help(str.<method-name>) to receive documentation on an individual method

Extracting a filename's extension

  • Result of 'myfile.txt'.split('.') is ['myfile', 'txt']
  • Result of 'myfile.html'.split('.') is ['myfile', 'html']
  • The subscript [-1] extracts the last element.
  • This can be used to extract a filename extension.

Text Files

  • A text file is a software object that stores data on permanent mediums like a disk or CD
  • Advantages of taking input data from a file are:
    • The data set can be much larger
    • The data can be input more quickly and with less chance of error
    • The data can be used repeatedly with the same program or with different programs

Text Files and Their Format

  • A text editor such as Notepad or TextEdit permits the creation, viewing, and saving of data in a text file.
  • A text file containing six floating-point numbers might look like: 34.6 22.33 66.75 77.12 21.44 44.87
  • Data output to or input from a text file must be strings.
  • Numbers must be converted to strings before output.

Writing Text to a File

  • Data can be output to a text file using a file object.
  • Open a file for output with f = open("myfile.txt", 'w').
    • If the file does not exist, it is created.
    • If the file already exists, Python opens it; when data are written to the file and the file is closed, any data previously existing in the file are erased.
  • f.write("First line.\nSecond line.\n") writes two lines of text to the file.
  • When all outputs are finished, use f.close() to close the file.

Writing Numbers to a File

  • The file method write expects a string as an argument.
  • Other types of data must first be converted to strings before being written to the output file. This can be done using str.

Reading Text from a File

  • Open a file for input with output = open("myfile.txt", 'r')
    • If the path name is not accessible from the current working directory, Python raises an error
  • f.read() is one way to read data from a file
    • After input is finished, read returns an empty string
  • Alternatively, a file may be read line by line, using f.readline()
    • The next code segment inputs lines of text with readline:
    • >> f = open("myfile.txt”, 'r')
    • >> while True:
    • line = f.readline()
    • if line == “”:
    • break
    • print(line)

Reading Numbers from a File

  • String representations of integers and floating-point numbers can be converted to the numbers by using the functions int and float.
  • Use the the code:
f = open("integers.txt", 'r')
theSum = 0
for line in f:
    line = line.strip()
    number = int(line)
    theSum += number
print(“The sum is”, theSum)
  • The next code segment modifies the previous one to handle integers separated by spaces and/or newlines
f = open("integers.txt", 'r')
theSum = 0
for line in f:
    wordlist = line.split()
    for word in wordlist:
        number = int(word)
        theSum += number
print(“The sum is”, theSum)

File Methods

Method What it Does
open(filename, mode) Opens a file at the given filename and returns a file object. The mode can be 'r', 'w', 'rw', or 'a'. The last two values mean read/write and append.
f.close() Closes an output file. Not needed for input files.
f.write(aString) Outputs aString to a file.
f.read() Inputs the contents of a file and returns them as a single string. Returns "" if the end of file is reached.
f.readline() Inputs a line of text and returns it as a string, including the newline. Returns "" if the end of file is reached.

Chapter Summary

  • A string is a sequence of zero or more characters
    • The len function returns the number of characters in its string argument
  • A string is an immutable data structure
  • The subscript operator [] can be used to access a character at a given position
    • Can also be used for slicing ([<start>:<end>])
  • in operator is used to detect the presence or absence of a substring in a string
  • Method: operation that is used with an object
  • The string type includes many useful methods for use with string objects
  • A text file is a software object that allows a program to transfer data to and from permanent storage
  • A file object is used to open a connection to a text file for input or output
    • Some useful methods: read, write, readline
  • for loop treats an input file as a sequence of lines
    • On each pass through the loop, the loop's variable is bound to a line of text read from the file

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

Description

Explore how to access individual characters and substrings within strings. Learn to use string methods for manipulation and perform searches. Also, learn about string structure, its length, and the usage of the len function.

More Like This

JavaScript String Manipulation Quiz
9 questions
Алгоритми рядків
10 questions
String Concatenation
14 questions
Use Quizgecko on...
Browser
Browser