Match capital and lowercase letters
Matching Uppercase and LowerCase Letters
This interactive and hands on game to teach matching uppercase and lowercase letters is a fun gross motor game for preschool and kindergarten. Use this interactive letter activity along as an alphabet matching with objects and a sensory-motor learning activity!
Matching uppercase letters to lowercase letters is a literacy task that supports reading skills, but also challenges visual discrimination skills, form constancy, and visual scanning, all of which are visual processing skills needed for handwriting and reading comprehension. What’s fun about this activity is that it builds these skills in a fun way!
Be sure to grab our color by letter worksheet to work on letter matching, visual discrimination skills.
Matching Uppercase and Lowercase Letters
Learning letters and matching upper and lower case letters is a Kindergarten skill that can be tricky for some kids. We made this easy prep letter identification activity using items you probably already have in the house. If you’ve seen our blog posts over the last few days, you’ve noticed we’re on a learning theme using free (or mostly free) items you probably already have.
We’re sharing 31 days of learning at home with free materials this month along with 25 other bloggers in the 31 days of homeschooling tips series.
Today’s easy letter learning activity can use any letters you have around the house or magnetic letters and coffee filters.
While this activity is almost free if you’ve got the items at home already, we’re sharing the affiliate links for the items in this post.
How to play this interactive letter matching activity
You’ll need just a few items for this letter matching activity:
- Magnetic letters
- marker
- coffee filters (but paper towels or recycled paper would work as well.
To set up the activity, there are just a few steps:
- Grab the magnetic letters from the fridge and 26 coffee filters.
- Use a permanent marker to write one lower case letter of the alphabet on each coffee filter.
- With your child, match the magnetic letters to the lowercase letters on the coffee filters.
- Ask the child to help you crumble each letter inside the coffee filter that has its matching lowercase letter.
- Continue the play!
More ways to match uppercase and lowercase letters
By matching the magnetic uppercase letter to the lowercase letter on the coffee filter, kids get a chance to incorporate whole body movements and gross motor activity while looking for matching letters.
With your child, first match up each lower case coffee filter letter to the upper case magnetic letter.
You can spread the filters out to encourage visual scanning and involve movement in the activity, OR you can stack the coffee filters in a pile and one by one match up the letters. This technique requires the child to visually scan for the upper case magnet letters.
Try both ways for more upper/lower case letter practice!
We then wrapped the coffee filters around the magnets in a little bundle. There are so many games you can play with these upper and lower case letters:
- Match the same letter– match uppercase letters to uppercase letters and lowercase letters to lowercase letters.
- Alphabet matching with objects– Match an object that starts with the letter of the alphabet. Use small objects inside the coffee filter and match it to lowercase letters written in the coffee filter with uppercase magnet letters.
- Match the picture with the letter– Print off pictures of words that start with each letter of the alphabet. Then match the picture with letters of the alphabet using lowercase letters written on the filter and uppercase letters in magnetic letter form.
- Play a letter memory game– Hide letters around the room and challenge kids to find the letters in order to match the uppercase letter to the lowercase letters.
- Letter sound matching– Make a letter sound and challenge kids to find the letter that makes that sound.
- Letter Hide and Seek- Hide the bundled up letters around the room while your child hides his eyes. Send him off to find the letters and ask him to open the bundle and identify the letter.
- Letter Toss Activity- Toss the coffee filter bundles into a bucket or bin. Any letters that make it into the bin are winners!
- Name the letters- Unwrap the bundles and name the letters. Spread the coffee filters out around the room. Toss magnetic letters onto the matching lower case letter.
- Letter toss game- Toss a bean bag onto the coffee filters. The child can identify the lower case letter, then go to the pile of magnetic letters and find the matching upper case letter.
Can you think of any more ways to work on upper and lower case letter matching with coffee filters and magnetic letters?
Matching Big and Small Letters
The nice thing about this activity is that you can teach the concepts of big and small letters. When we say “big letters” and “small letters”, we are showing the concept of letters that touch the top and bottom lines, or the upper case letters.
And teaching children the difference between those big letters and the small letters which touch just the middle point are part of the visual discrimination process that is needed for handwriting on the lines, or line awareness skills.
You will enjoy more alphabet posts from our archives:
- Hand-eye coordination letter match
- Building letters with baked cotton swabs
Looking for more interactive letter activities to match uppercase and lowercase letters? The Letters! Fine Motor Kit is for you!
Letter Kit for fine motor, visual motor, and sensory motor play.This 100 page printable packet includes everything you need for hands-on letter learning and multisensory handwriting!
This digital and printable packet includes these multisensory handwriting and letter formation materials:
- A-Z Multisensory Writing Pages
- Alphabet Fine Motor Clip Cards
- Cut and place Fine Motor Mazes
- A-Z Cotton Swab Cards
- A-Z Pattern Block Cards
- Fine Motor Letter Geo-Cards
- A-Z Color and Cut Letter Memory Cards
- Color By Size Sheets
- A-Z Building Block Cards
- A-Z Play Dough Letter Formation Cards
- Graded Lines Box Writing Sheets
- Alphabet Roll and Write Sheets
- Pencil Control Letter Scan
- Color and Cut Puzzles
6 Upper and Lower Case Letter Matching Activities for Preschool
Letter matching activities are an excellent way for preschoolers to explore the alphabet. This is a very basic and easy upper and lowercase letter matching activity to reinforce matching letters of the alphabet in a fun way that preschoolers enjoy.
Use this FREE printable upper and lowercase letter matching activity to help solidify letter recognition in your preschool kids to help prepare them for reading.
Don’t forget to grab your FREE upper and lower case letter matching printable at the end of this post!
Free Printable Letter Matching Activity!
Young children are naturally fascinated by the letters of the alphabet. Have you ever been driving when your preschooler points to a stop sign and says, “Look, Mom! S! My name has s in it!”
Even children as young as two years may begin naming and recognizing letters, especially those in their names or those that are frequently found in their environment. (Although let me be clear that is it completely OK if they aren’t). Those are always their favorite letters.
Upper and Lowercase Letter Matching Activities for Preschool
Typically upper case letters are easier for children to learn because the straight lines and familiar “o” shapes are easier for children to recall than lower case letters which are often a mix of various shapes. Take the letter “g” for example. It has an “o” shape, a straight line, and then a hook for the tail. All those together is more difficult for a preschooler to learn than an upper case G which is mostly an “o” shape.
But soon, preschoolers are ready to begin matching upper and lower case letters, and letter matching activities like this one are a great place to start.
This free alphabet printable follows the same letter order as my preschool phonics curriculum. In my phonics lesson plans, preschoolers are introduced to letters in the order of frequency of use in the English language. That way, if you happen to have a preschooler who is developmentally ready to start decoding words, she will already have a handful of sounds that when combined make up a lot of words!
You might also like:
These are posts that teach children how to spell their names, or teach the letters of their name.
Letter Tile Names – A Name Recognition Activity
Mosaic Letters
Tape Resist Name and Phonics Booklets
Materials for Letter Matching Activities
My favorite letter matching activities are simple and quick to prepare. You only need a few items.
- FREE letter matching printable (found at the end of this post)
- Laminator and laminating pockets (optional)
- Glue sticks
- Tray (This helps preschoolers define their workspace).
Set-Up the Letter Matching Activity
Print out your uppercase and lowercase letter matching printable. (Remember, it’s free and at the end of this post). Cut them into letter tiles. (This is my all-time favorite paper cutter!)
I like to laminate my cards so that kids can use them over and over again, but you can also use glue sticks to glue the letters in place if you don’t want to go to the trouble of laminating the cards. And parents like it when their kiddos bring home a letter identification activity like this one.
Give each child a single grid, 15 corresponding letter tiles, and a glue stick all placed on a tray (skip the glue sticks if you’re doing this activity as a laminated activity).
My little disclaimers for the preparation
Don’t forget to grab your FREE upper and lower case letter matching printable at the end of this post!
To save time (and prevent potential accidents) I cut out the letter tiles in advance for my 3’s class. However, if doing this activity with a 4-5’s class, I would have had the students do their own cutting. (I keep all those kid scissors organized with this colorful caddy.)
Kindergarten teachers really appreciate it when preschoolers have good scissor control. (Need some tips? Check out this post!)
The Letter Matching Activity (with FREE Printable)
The object of the activity comes in two strides.
First, have your students identify each upper case letter on the grid. With the repetition of the four letters throughout the grid, identification of the letters ia solidified.
Next, show your students how to identify the lower case letters on the letter tiles and match with the upper case letters by gluing it on the grid.
To prevent random gluing, (as I knew some students would immediately gravitate to), I made an extra copy of the activity and modeled it for the students.
Once I modeled the concept with each letter, I asked the students to help me with the remaining letters. This is a traditional “I Do, Let’s Do it Together, You Do” teaching strategy). This ensured that all students knew exactly what to do when they received their own materials.
I offered this activity to my three-year-old preschool class. While I was expecting it to be difficult for some of my students, it was received rather well.
Surprisingly, our biggest challenge was not the matching of upper and lower case letters. Instead, it was learning to paste the letter tiles on the grid correctly.
You know, put the glue on the back of the tile, not the front, and put the tile right-side-up? Just the little things you wouldn’t think would be a challenge, haha!
More Letter Matching Activities
Don’t forget to grab your FREE upper and lower case letter matching printable at the end of this post!
And more ways to use this printable! After all, a printable is only a good one if it meets your needs, so here are some ways to scaffold the matching activity to different learners.
- Invite individual students to name specific letters as you point to them.
- Challenge your students to also think of something that begins with that letter. (Check out this letter/sound activity, too!)
- For younger learners, have the children sort their letters into piles before they begin gluing. Then they only have to worry about finding one kind of letter at a time. It’s less overwhelming that way.
- Use the letter tiles to spell out sight words or easy CVC words.
- When the grid is completed, invite your preschoolers to find small toys that begin with each letter and place them on the corresponding tiles.
Don’t forget to grab your free printable at the end of this post, and then keep reading for more letter matching activities!
You might also like
These are some of my most popular letter matching activities for preschoolers.
Rainbow Letters Race to the Top (FREE Printable)
I Spy Letters – A Letter Identification Activity for Preschoolers
Alphabet Circle Seek
The Benefits of Letter Matching
Thinking of objects that begin with the letter sound I was pointing to was difficult for the students. This is because it’s a skill that typically isn’t mastered until late preschool or not even until kindergarten for a lot of children. But this was a quick way for me to informally assess their letter/sound knowledge.
And, when I named a word, my three-year-old students were easily able to identify if that word began with the same letter to which I was pointing. This is just like our sound matching activity I threw together with just a set of animals toys and a lot like our flashcard practice.
This letter matching activity was an effective way to reinforce the letters we had been studying. It was an excellent review and the students were proud of their completed work and put it on display.
You might also like
ABC Letter Stack Game
Letter Sound Matching Activity
Initial Sound Object Matching
Grab Your FREE Letter Matching Printable
Remember, this FREE letter matching printable practices the alphabet in the same order I introduce them in my preschool literacy curriculum, which makes these perfect for each review week!
Don’t forget to keep reading for more letter matching activities!
Looking for More Letter Matching Activities?
You might enjoy these other letter matching printables. I like to use these as literacy centers.
Want the Complete Preschool Curriculum?
You’ve got it!
The Complete Preschool Curriculum has everything you need to teach your preschoolers literacy and math in a fun and engaging way, without all the boring worksheets!
This resource includes 36 weeks of:
- oral language lessons
- phonological awareness lessons
- phonics lessons
- math lessons from all five disciplines of math (number sense, algebra, geometry, measurement, and data analysis)
- 10 weekly alphabet, letter formation, and beginning sounds centers
- 72 math centers to support all five disciplines of math
- editable preschool portfolio
- editable preschool portfolio monthly planning checklist
With detailed lesson plans offering an array of daily teaching options, you can cut your lesson planning down to a fraction of the time while still offering your preschoolers the best possible learning experience.
Click the image below to learn more!
Join thousands of others!
Subscribe to get our latest content by email.
We won't send you spam. Unsubscribe at any time. Powered by ConvertKitSarah Punkoney, MAT
I’m Sarah, an educator turned stay-at-home-mama of five! I’m the owner and creator of Stay At Home Educator, a website about intentional teaching and purposeful learning in the early childhood years. I’ve taught a range of levels, from preschool to college and a little bit of everything in between. Right now my focus is teaching my children and running a preschool from my home. Credentials include: Bachelors in Art, Masters in Curriculum and Instruction.
stayathomeeducator.com/
Uppercase and Lowercase Letters / Sudo Null IT News
I've gathered here some not-so-obvious facts about uppercase and lowercase letters that a programmer may encounter at work. Many of you have translated strings into “all uppercase” (uppercase), “all lowercase” (lowercase), “first capital, and the rest lowercase” (titlecase). Even more popular is the case-insensitive comparison operation. On a global scale, such operations can be quite non-trivial. The post is structured as a "collection of misconceptions" with counterexamples. nine0003
1. If I convert the string to uppercase or lowercase, the number of Unicode characters does not change.
No. The text may contain lowercase ligatures, which do not correspond to one character in upper case. For example, when translating to uppercase: fi (U+FB00) -> FI (U+0046, U+0049)
2. Ligatures are a perversion, no one uses them. If they are not taken into account, then I'm right.
No. Some letters with diacritics do not have an exact match in other case, so you have to use a combined character. Let's say the Afrikaans language has the letter ʼn (U+0149). In upper case, it corresponds to a combination of two characters: (U+02BC, U+004E). If you come across a transliteration of Arabic text, you may encounter (U+1E96), which also does not have a single-character match in upper case, so you will have to replace it with (U+0048, U+0331). The Wakhi language has a letter (U+01F0) with a similar problem. You may argue that this is exotic, but there are 23,000 articles in Afrikaans on Wikipedia.
3. All right, but let's consider a combined character (involving modifying or combining code points) as one character. Then the length will still be preserved. nine0005
No. There is, for example, the letter "escet" ß (U+00DF) in German. When converted to uppercase, it turns into two SS characters (U+0053, U+0053).
4. Okay, okay, got it. We will assume that the number of Unicode characters can increase, but not more than twice.
No. There are specific Greek letters, for example, (U+0390) that turn into three Unicode characters (U+0399, U+0308, U+0301)
5.
Let's talk about titlecase. Everything is simple here: I took the first character from the word, translated it into uppercase, took all the subsequent ones, translated it into lowercase. nine0005No. Let's remember the same ligatures. If a word in lowercase begins with fl (U+FB02), then in uppercase the ligature becomes FL (U+0046, U+004C), but in titlecase it becomes Fl (U+0046, U+006C). The same with ß, but, theoretically, words cannot begin with it.
6. Those ligatures again! Well, we take the first character from the word, translate it into uppercase, if more than one character is obtained, then we leave the first one, and the rest back into lowercase. Then it will definitely work.
Won't work. There is, for example, the digraph dz (U+01F3), which can be used in text in Polish, Slovak, Macedonian or Hungarian. In uppercase it corresponds to the digraph DZ (U+01F1), and in titlecase it corresponds to the digraph Dz (U+01F2). There are other digraphs. The Greek language, on the other hand, will please you with jokes with hypogegrammen and progegrammen (fortunately, this is rarely found in modern texts). In general, the uppercase and titlecase variants for a character can be different, and there are separate entries for them in the Unicode standard. nine0003
7. Good, but at least the result of converting a character's case to uppercase or lowercase does not depend on its position in the word.
No. For example, the Greek capital sigma Σ (U+03A3) becomes a lowercase ς (U+03C2) at the end of a word and σ (U+03C3) in the middle.
8. Oh, okay, let's process the Greek sigma separately. But in any case, the same character in the same position in the text is converted in the same way.
No. For example, in most Latin languages, the lower case for I (U+0049) is i (U+0069), but not in Turkish and Azeri. There, the lower case for I is ı (U+0131) and the capital case for i is İ (U+0130). In Turkey, because of this, enchanting bugs are sometimes observed in a variety of software. And if you come across a text in Lithuanian with accents, then, for example, a capital Ì (U + 00CC), which will turn not into ì (U + 00EC), but into (U + 0069, U + 0307, U + 0300) . In general, the result of the conversion also depends on the language. Most of the complex cases are described here.
9. What a horror! Well, let's now correctly convert to uppercase and lowercase. Comparing two words case-insensitively is not a problem: we translate both into lowercase and compare.
There are also many pitfalls that follow from the above. For example, it will not work with German straße and STRASSE (the former will not change, the latter will turn into strasse). There will also be problems with many of the other letters described above.
10. M-yes… Maybe then everything is in the uppercase? nine0005
And it won't always work (although much more often). But, say, if you come across the notation STRAE (yes, there is a big escet in German and Unicode too), it will not match straße. For comparisons, letters are converted according to a special Unicode table - CaseFolding, according to which both ß and SS will turn into ss.
11. A-ah-ah, this is some kind of kapets!
Here I agree.
If some symbols are not displayed for someone, write me a private message, I will replace it with a picture. nine0084 not are 1:1 display or reversible. Most of these operations are for display, not normalization.
Methods casefold (), upper(), lower(), capitalize(), title(), swapcase()
str.casefold()
- creates a string string, which is suitable for the case of insensitive comparisons. This is more aggressive than str.lower
and may change strings that are already lowercase or cause strings to grow in length and are not intended to be displayed. nine0003
"XßΣ".casefold() # 'xssσ' "XßΣ".lower() # 'xßς'
The transformations that occur within casefolding are defined by the Unicode Consortium in the CaseFolding.txt file on their website.
str.upper()
- takes each character in a string and converts it to its uppercase equivalent, for example:
"This is a 'string'.".upper() # "THIS IS A 'STRING'."
str.lower()
- does the opposite; it takes each character in a string and converts it to its lowercase equivalent:
"This IS a 'string'.".lower() # "this is a 'string'."
str.capitalize()
- returns the capitalized version of the string, that is, it makes the first character uppercase and the rest lowercase:
"this Is A 'String'.".capitalize() # Capitalizes the first character and lowercases all others # "This is a 'string'."
str.title()
- returns the title of the cased version of the string, i.e. each letter at the beginning of a word is made in upper case and all the rest are made in lower case:
"this Is a 'String'". title() # "This Is A 'String'"
str.swapcase()
- str.swapcase
returns a new string object with all lowercase characters swapped to uppercase and all uppercase characters swapped to lowercase:
" this iS A STRiNG".swapcase() #Swaps case of each character # "THIS Is a strIng"
Use as str
class methods
Note that these methods can be called either on string objects (as shown above) or as a class method of str
class (with an explicit call to str.upper
etc.)
str.upper("This is a 'string'") # "THIS IS A 'STRING'"
This is especially useful when applying one of these methods to many strings at once, say map
functions.
map(str.upper,["These","are","some","'strings'"]) # ['THESE', 'ARE', 'SOME', "'STRINGS'"]
Split a string based on delimiter into a list of strings
str.split(sep=None, maxsplit=-1)
str. split
takes a string and returns a list of substrings of the original string. The behavior differs depending on whether the sep
argument is provided or omitted.
If sep
is not provided, or if None
is not present, then splitting occurs wherever there are spaces. However, leading and trailing spaces are ignored, and multiple consecutive whitespace characters are treated the same as a single whitespace character:
"This is a sentence.".split() # ['This', 'is', 'a', 'sentence.'] " This is a sentence. ".split() # ['This', 'is', 'a', 'sentence.'] " ".split() #[] nine0097
sep
parameter can be used to define a delimiter string. The source string is split where the separator string occurs, and the separator itself is discarded. Multiple consecutive delimiters not are treated the same way as a single one, but rather cause empty strings to be created."This is a sentence.".split('') # ['This', 'is', 'a', 'sentence. '] "Earth,Stars,Sun,Moon".split(',') # ['Earth', 'Stars', 'Sun', 'Moon'] " This is a sentence. ".split('') # ['', 'This', 'is', '', '', '', 'a', 'sentence.', '', ''] "This is a sentence.".split('e') # ['This is a s', 'nt', 'nc', '.'] "This is a sentence.".split('en') # ['This is a s', 't', 'ce.']The default is to split by every occurrence of a delimiter, however the
maxsplit
parameter limits the number of splits that occur. The default value-1
means there is no limit:"This is a sentence.".split('e', maxsplit=0) # ['This is a sentence.'] "This is a sentence.".split('e', maxsplit=1) # ['This is a s', 'ntence.'] "This is a sentence.".split('e', maxsplit=2) # ['This is a s', 'nt', 'nce.'] "This is a sentence.".split('e', maxsplit=-1) # ['This is a s', 'nt', 'nc', '.']
str.rsplit(sep=None, maxsplit=-1)
str.rsplit
("right split") is different fromstr.split
("left split") whenmaxsplit
is specified. Splitting starts at the end of the string, not at the beginning:"This is a sentence.".rsplit('e', maxsplit=1) # ['This is a sentenc', '.'] "This is a sentence.".rsplit('e', maxsplit=2) # ['This is a sent', 'nc', '.']Note: Python defines a maximum number of splits are performed, while most other programming languages specify a maximum number of substrings created. This can create confusion when porting or comparing code.
Replace all occurrences of one substring with another substring
Python's
str
type also has a method for replacing occurrences of one substring with another substring in a given string. For more complex cases,re.sub
can be used.str.replace(old, new[ count])
:
str.replace
takes two arguments,old
andnew
, containing theold
substring to be replaced with thenew
substring. The optional argumentcount
specifies the number of replacements to be:For example, in order to replace
'foo'
with'spam'
in the next line, we can callstr.replace
withold = 'foo ' nine0060 and
new = 'spam'
:"Make sure to foo your sentence.".replace('foo', 'spam') # "Make sure to spam your sentence."If the given string contains multiple examples that match
old
the argument, all occurrences are replaced by the value supplied innew
:"It can foo multiple examples of foo if you want.".replace('foo', 'spam') # "It can spam multiple examples of spam if you want."unless of course we supply a value for
count
. In this case,count
entries are going to be replaced:"""It can foo multiple examples of foo if you want, \ or you can limit the foo with the third argument.""". replace('foo', 'spam', 1) # 'It can spam multiple examples of foo if you want, or you can limit the foo with the third argument.'str.format and f-strings: format values to string
Python provides string interpolation and formatting functionality via
str.format
function introduced in version 2.6 and F-strings introduced in version 3.6.The following variables are given:
i = 10 f = 1.5 s = "foo" l = ['a', 1, 2] d = {'a': 1, 2: 'foo'}Let's see different formatting of the string
"{} {} {} {} {}". format(i, f, s, l, d) str.format("{} {} {} {} {}", i, f, s, l, d) "{0} {1} {2} {3} {4}". format(i, f, s, l, d) "{0:d} {1:0.1f} {2} {3!r} {4!r}".format(i, f, s, l, d) "{i:d} {f:0.1f} {s} {l!r} {d!r}".format(i=i, f=f, s=s, l=l, d=d)All statements above are equivalent
"10 1.5 foo ['a', 1, 2] {'a': 1, 2: 'foo'}"
f"{i} {f} {s} { l}{d}" f"{i:d} {f:0.1f} {s} {l!r} {d!r}"For reference, Python also supports C-style classifiers for string formatting. The examples below are equivalent to those above, but the
str.format
variants are preferred due to advantages in flexibility, notation consistency, and extensibility:"%d %0.1f %s %r %r" % (i, f, s, l, d) "%(i)d %(f)0.1f %(s)s %(l)r %(d)r" % dict(i=i, f=f, s=s, l=l, d=d )Parentheses are used for interpolation in
str.format
can also be numbered to reduce duplication when formatting strings. For example, the following is equivalent to:"I am from {}. I love cupcakes from {}!".format("Australia", "Australia") #"I am from Australia. I love cupcakes from Australia!" "I am from {0}. I love cupcakes from {0}!".format("Australia") #"I am from Australia. I love cupcakes from Australia!" nine0097While the official python documentation is thorough as usual, pyformat.info has a large set of examples with detailed explanations.
In addition,
{
and}
characters can be escaped using double brackets:"{{'{}': {}, '{}': {}}}". format("a" , 5, "b", 6) # "{'a': 5, 'b': 6}"See Format string for more information.
str.format()
was proposed in PEP 3101 and F-strings in PEP 498 .Counting the number of occurrences of a substring in a string
One method is available for counting the number of occurrences of a substring in another string,
str.count
.str.count(sub[ start[ end]])
str.count
returnsint
indicating the number of non-overlapping occurrences of substringssub
in another string. The optional argumentsstart
andend
indicate the start and end at which the search will occur. Defaultstart = 0
andend = len(str)
means the entire string will be searched:s = "She sells seashells by the seashore." s.count("sh") #2 s.count("se") #3 s.count("sea") #2 s.count("seashells") # 1By giving different values for
start
,end
, we can get a more localized lookup and count, for example ifstart
is equal to13
call to:s. count("sea", start) # 1is equivalent to:
t = s[start:] t.count("sea") # 1Check the start and end characters of a string
To check the start and end of a given string in Python, you can use the
str.startswith()
andstr.endswith()
methods.str.startswith(prefix[ start[ end]])
As the name implies,
str.startswith
is used to check if the given string starts with the given characters inprefix
.s = "This is a test string" s.startswith("T") # True s.startswith("Thi") # True s.startswith("thi") # FalseThe optional arguments
start
andend
specify the start and end points from which testing will start and end. In the following example, by giving a start value of2
our string will be looked up from position2
and then:s.startswith("is", 2) # TrueThis gives
True
sinces[2] == 'i'
ands[3] == 's'
.You can also use
tuple
to check if it starts with any of the stringsets.startswith(('This', 'That')) # True s.startswith(('ab', 'bc')) # False
str.endswith(prefix[ start[ end]])
- exactly likestr.startswith
with the only difference that it looks for ending characters and not starting characters. For example, to check if a string ends with a full stop, you can write:s = "this ends in a full stop." s.endswith('.') # True s.endswith('!') # Falseas with
startswith
more than one character can be used to end a sequence:s.endswith('stop.') # True s.endswith('Stop.') # FalseYou can also use
tuple
to check if it ends with any of the stringsets.endswith(('.', 'something')) # True s.endswith(('ab', 'bc')) # FalseCheck what string 9 consists ofThe 0054
Python
str
type also has a number of methods that can be used to evaluate the contents of a string. These arestr.isalpha
,str.isdigit
,str.isalnum
,str.isspace
. The capitalization can be checked withstr.isupper
,str.islower
andstr.islower
andstr.isalnum
str.isalpha
str.isalpha
takes no arguments and returnsTrue
if all characters in the given string are alphabetic, for example:"Hello World".isalpha() # contains a space # False "Hello2World".isalpha() # contains a number # False "HelloWorld!".isalpha() # contains punctuation # False "HelloWorld".isalpha() # TrueIn the edge case, an empty string evaluates to
False
when using"".isalpha()
.str.isupper
,str.islower
,str.istitle
These methods check for the use of capital letters in a given string.
str.isupper
is a method that returnsTrue
if all characters in the given string are uppercase andFalse
otherwise."HeLLO WORLD".isupper() # False "HELLO WORLD".isupper() # True "".isupper() # FalseOn the other hand,
str.islower
is a method that returnsTrue
if all characters in the given string are lowercase andFalse
otherwise."Hello world".islower() # False "hello world".islower() # True "".islower() # False
str.istitle
returnsTrue
if the given title string is cased; that is, each word begins with an uppercase letter followed by lowercase letters."hello world".istitle() # False "Hello world".istitle() # False "Hello World".istitle() # True "".istitle() FalseMethods str.isdecimal , str.isdigit , str.isnumeric
str.isdecimal
returns a string whether a sequence of decimal digits is suitable for representing a decimal number. nine0003
str.isdigit
includes a digit not in a form suitable for representing a decimal number, such as superscript digits.
str.isnumeric
includes any numeric value, even if not numeric, such as values outside the range 0-9.isdecimal isdigit isnumeric 12345 True True True ១2҃໔5 True True True ①²³🄅₅ False True True ⑩⒓ False False True Five False False False nine0097Byte strings (
bytes
in Python 3,str
in Python 2), only supportsisdigit
, which only checks for basic ASCII digits.Like
str.isalpha
an empty string evaluates toFalse
.str.isalnum
This is a combination of
str.isalpha
andstr.isnumeric
, specifically it has the valueTrue
if all characters in the given string are literal - numeric, i.e. they consist of alphabetic or numeric characters:"Hello2World".isalnum() # True "HelloWorld".isalnum() # True "2022".isalnum() # True "Hello World".isalnum() # contains whitespace # False
str. isspace
- ReturnsTrue
if the string contains only whitespace characters."\t\r\n".isspace() # True " ".isspace() # TrueSometimes a string looks "empty" but we don't know if it is because it contains only spaces or no characters at all
"".isspace() # FalseTo cover this case we need an extra test
my_str = '' my_str.isspace() # False my_str.isspace() or not my_str # TrueBut the shortest way to check if a string is empty or contains only whitespace characters is to use
strip
(with no arguments it strips all leading and trailing whitespace characters)not my_str.strip() # Truestr.translate: translate characters in string
Python supports a
translate
method on thestr
type, which allows you to specify a translation table (used for replacement), as well as any characters to be removed in the process.9The 0048
str.translate(table[ deletechars])
- parametertable
is a lookup table that defines the mapping from one character to another.deletechars
is a list of characters to be removed from the string.maketrans
method (str.maketrans
in Python 3 andstring.maketrans
in Python 2) allows you to create a translation table.translation_table = str.maketrans("aeiou", "12345") my_string = "This is a string!" translated = my_string.translate(translation_table) # 'Th4s 3s 1 str3ng!' The
translate
method returns a string that is a translated copy of the original string. You can settable
argumentNone
if only required to remove characters.'this syntax is very useful'.translate(None, 'aeiou') 'ths syntx s vry sfl'Remove unwanted leading/trailing characters from a string
Three methods provided that offer the ability to strip leading and trailing characters from a string:
str.strip
,str.rstrip
andstr. lstrip
All three methods have the same signature, and all three return a new string object with unwanted characters removed. nine0059 str.strip([chars])
str.strip
acts on the given string and removes (strips) or any leading trailing characters contained in the argumentchars
; ifchars
is not included or there is noNone
, all whitespace characters are removed by default. For example:" a line with leading and trailing space ".strip() # 'a line with leading and trailing space'If chars
are supplied, all characters contained in it are removed from the string that is returned. For example:
">>> a Python prompt".strip('>') # strips the '>' character and the space after it #'a Python prompt'
str.rstrip([chars])
andstr.lstrip([chars])
- These methods have the same semantics and arguments asstr.strip()
, their difference lies in the direction they come from begin.str.rstrip()
starts from the end of the string whilestr. lstrip()
splits from the beginning of the string.For example, when using
str.rstrip
:" spacious string ".rstrip() # ' spacious string'While using
str.lstrip
:" spacious string ".rstrip() # 'spacious string' " spacious string ".rstrip().lstrip() # 'spacious string'Case-insensitive string comparison
Case-insensitive string comparison seems trivial, but it's not. This section only covers Unicode strings (the default in Python 3). Note that Python 2 may have minor drawbacks compared to Python 3 - the later handling of unicode is much more complete. nine0003
The first thing to note is that unicode case-removal conversions are not trivial. There is a text for which
text.lower() != text.upper().lower()
, For example,"ß"
:>>> "ß".lower() 'ß' >>> "ß".upper().lower() 'ss'But suppose you wanted to case insensitively compare
"BUSSE"
and"Buße"
. Heck, you probably also want to compare"BUSSE"
and"BUẞE"
equal - this is a new form of capital. The recommended way is to usecasefold
:help(str.casefold) """ Help on method_descriptor: casefold(self, /) Return a version of the string suitable for caseless comparisons """Don't just use
lower
. Ifcasefold
isn't available, doing.upper().lower()
helps (but only a little).Then you should consider accents. If the font renderer is fine, you probably think
"ê" == "ê"
- but it's not true :"ê" == "ê" # FalseThis is because they are actually
unicodedata [unicodedata.name(char) for char in "ê"] # ['LATIN SMALL LETTER E WITH CIRCUMFLEX'] [unicodedata.name(char) for char in "ê"] # ['LATIN SMALL LETTER E', 'COMBINING CIRCUMFLEX ACCENT'The easiest way to deal with this is
unicodedata.normalize
. You probably want to use NFKD normalization, but feel free to check the documentation. Then oneunicodedata.normalize("NFKD", "ê") == unicodedata.normalize("NFKD", "ê") # TrueTo finish, this is expressed in functions here:
import unicodedata def normalize_caseless(text): return unicodedata.normalize("NFKD", text.casefold()) def caseless_equal(left, right): return normalize_caseless(left) == normalize_caseless(right)Concatenate a list of strings into one string
A string can be used as a delimiter to join a list of strings together into one string with
join()
method. For example, you can create a string where each element in the list is separated by a space." ".join(["once","upon","a","time"]) # "once upon a time"In the following example, string elements are separated by three hyphens.
"---".join(["once", "upon", "a", "time"]) # "once---upon---a---time"Useful string module constants
Python
string
The Python module provides constants for operations involving strings. To use them, importstring
module:import stringCombination of
ascii_lowercase
andascii_uppercase
:string.ascii_letters # 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_lowercase
:Contains all ASCII lowercase characters:
string.ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase
:Contains all uppercase ASCII characters:
string.ascii_uppercase # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits
- contains all decimal digits:string.digits # '0123456789'
string.hexdigits
- contains all hex characters:string.hexdigits # '0123456789abcdefABCDEF'
string.octaldigits
- contains all octal characters:string.octaldigits # '01234567'
string.punctuation
- contains all characters that are considered punctuation in 9_`{|}~'
string. whitespace
- contains all ASCII characters that are considered whitespace:string.whitespace # ' \t\n\r\x0b\x0c'In script mode,
print(string.whitespace)
will print the actual characters, usestr
to get the above string returned.
string.printable
- contains all characters that are considered printable; combination ofstring.digits
,string.ascii_letters 9_`{|}~ \t\n\r\x0b\x0c'
Reversing a string (reverse)
A string can be reversed using the built-in function
reversed()
, which takes a string and returns an iterator in reverse order.reversed('hello') #[char for char in reversed('hello')] # ['o', 'l', 'l', 'e', 'h']
reversed()
can be wrapped in a''.join()
call to make a string from an iterator. nine0003''.join(reversed('hello')) # 'olleh'While using
reversed()
may be more readable for uninitiated Python users, using extended slicing in increments of-1
is faster and more concise. Here, try implementing this as a function:def reversed_string(main_string): return main_string[::-1] reversed_string('hello') # 'olleh'Line alignment
Python provides functions for line alignment, allowing you to pad text to make it easier to align different lines. nine0003
Here is an example of
str.ljust
andstr.rjust
:interstates_lengths = { 5: (1381, 2222), 19:(63, 102), 40: (2555, 4112), 93: (189.305) } for road, length in interstates_lengths.items(): miles,kms = length print('{} -> {} mi.({} km.)'.format(str(road).rjust(4), str(miles).ljust(4), str(kms).ljust(4) )) # 5 -> 1381 mi. (2222 km.) # 19 -> 63 mi. (102 km.) # 40 -> 2555 mi. (4112 km.) # 93 -> 189 mi. (305 km.) nine0097
ljust
andrjust
are very similar. Both have awidth
parameter and an optionalfillchar
parameter. Any string generated by these functions is at least as long as thewidth
parameter that was passed into the function. If the string is longer thanwidth
alread, it is not truncated.fillchar
argument that defaults to a space character' '
must be a single character, not a multicharacter string. nine0003
ljust
end-of-line pad function it is called on withfillchar
untilwidth
character length.rjust
function to pad the beginning of a line in a similar manner. Thus,l
andr
in the names of these functions refer to the side that the source string, and notfillchar
, is located in the output string.Convert between str or byte data and unicode characters
The contents of files and network messages can be encoded characters. They often need to be converted to unicode to display correctly.
In Python 3, you may need to convert byte arrays (called "byte literal") to Unicode character strings. The default is now a Unicode string, and byte string literals must now be entered as
b''
,b""
, etc. Byte literal will returnTrue
inisinstance(some_val, byte)
, assumingsome_val
to be a string that can be encoded in bytes.# You get from file or network "© abc" encoded in UTF-8 s = b'\xc2\xa9 abc' # s is a byte array, not characters # In Python 3, the default string literal is Unicode; byte array literals need a leading b s[0] # b'\xc2' - meaningless byte (without context such as an encoding) type(s) # bytes - now that byte arrays are explicit, Python can show that. u = s.decode('utf-8') # '© abc' on a Unicode terminal # bytes.decode converts a byte array to a string (which would be Unicode in Python 3) u[0] # '\u00a9' - Unicode Character 'COPYRIGHT SIGN' (U+00A9) '©' type(u) # str # The default string literal in Python 3 is UTF-8 Unicode. u.encode('utf-8') # b'\xc2\xa9 abc' # str.encode produces a byte array, showing the ASCII-range bytes as non-replaceable characters.