livepython.net
CHAPTER 12Working With Strings
12.5  PRACTICE

Python String Practice Questions for Beginners

Chapter 12 Recap and Practice

You can now take strings apart, clean them up and print them neatly. Here is the chapter in one table:

You writeIt does
s[0], s[-1]the first and the last character
s[2:5], s[:3], s[3:]a slice: from start up to, not including, stop
s[::-1]the string backwards
s = "B" + s[1:]strings are immutable: build a new one instead of changing a letter
for ch in s:visit every character, left to right
"Py" in sTrue if the piece is anywhere in the string
s.upper(), s.lower(), s.title()a new string with the capitals changed
s.strip()a new string without the spaces at the ends
s.replace("a", "o")a new string with every match swapped
s.find("@"), s.count("m")where a piece is (or -1), and how many times
s.startswith("x"), s.endswith("x")True or False
s.isdigit(), s.isalpha()check text before you use it
s.split(), s.split(",")cut a string into a list of strings
" ".join(words)glue a list of strings with a separator
{x:10}, {x:<10}, {x:>10}, {x:^10}a width, and where the value sits in it
{x:,.2f}thousands commas and two decimals

And remember: string methods never change the string. Store the new string they give you.

Practice questions

Use input() with no prompt text. The tests try several inputs, often with extra spaces or odd capitals, so test your program with those too. When the output is a table, every space counts.

Index and slice strings

  1. 100.Python Program to Print the First and Last Character of a StringEasySolve
  2. 101.Python Program to Check if a String Is a PalindromeMediumSolve

String methods

  1. 102.Python Program to Clean Up a Name with strip() and title()EasySolve
  2. 103.Python Program to Count the Vowels in a SentenceMediumSolve
  3. 104.Python Program to Check a Simple Email AddressMediumSolve

Split and join

  1. 105.Python Program to Count the Words in a SentenceEasySolve
  2. 106.Python Program to Reverse the Words in a SentenceMediumSolve

f-string formatting

  1. 107.Python Program to Format a Number with CommasEasySolve
  2. 108.Python Program to Print a Multiplication Table in ColumnsMediumSolve
  3. 109.Python Program to Print a Neat Bill from Input LinesHardSolve

Text is everywhere in programs. Next, you'll learn dictionaries: a way to look up a value by its name.