String length with a loop

String length with a loop

EasyString Programs · 9 of 106

Write a Python program to calculate the length of a string with a loop instead of len().

Input
"sqatools"
Output
8 True

Approach

  1. Count the characters one by one.

Solution

Python
text = "sqatools"count = 0for _ in text:    count += 1print(count, count == len(text))
Output
8 True

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Longest and shortest word

Longest and shortest word

EasyString Programs · 7 of 106

Write a Python program to find the longest and the shortest word in a string.

Input
"Python makes string handling easy"
Output
Longest: handling
Shortest: easy

Approach

  1. Split into words and use max / min with key=len.

Solution

Python
text = "Python makes string handling easy"words = text.split()print("Longest:", max(words, key=len))print("Shortest:", min(words, key=len))
Output
Longest: handling
Shortest: easy

Line by line

Lines 3-4

key=len compares words by their length; on a tie, the first such word wins.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Vowel or consonant

Vowel or consonant

EasyString Programs · 6 of 106

Write a Python program to test whether a letter is a vowel or a consonant.

Input
"e", "K", "3"
Output
e -> vowel
K -> consonant
3 -> not a single letter

Approach

  1. Reject non-letters, then check membership in “aeiou”.

Solution

Python
def kind(ch):    if not ch.isalpha() or len(ch) != 1:        return "not a single letter"    return "vowel" if ch.lower() in "aeiou" else "consonant" for ch in ["e", "K", "3"]:    print(ch, "->", kind(ch))
Output
e -> vowel
K -> consonant
3 -> not a single letter

Line by line

Lines 2-3

Digits, symbols and longer strings are rejected first.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Count occurrences of a substring

Count occurrences of a substring

EasyString Programs · 5 of 106

Write a Python program to count how many times a substring occurs in a string.

Input
text = "the cat sat on the mat with the hat", sub = "the"
Output
3
4

Approach

  1. Use str.count().

Solution

Python
text = "the cat sat on the mat with the hat"print(text.count("the"))print(text.count("at"))
Output
3
4

Line by line

Line 2

count() counts non-overlapping occurrences.

Note

Because matches do not overlap, "aaaa".count("aa") is 2, not 3.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Reverse a string if its length is a multiple of 4

Reverse a string if its length is a multiple of 4

EasyString Programs · 4 of 106

Write a Python program to reverse a string if its length is a multiple of 4; otherwise return it unchanged.

Input
"Python", "sqatools"
Output
Python -> Python
sqatools -> slootaqs

Approach

  1. Check len(text) % 4 == 0, then reverse with [::-1].

Solution

Python
for text in ["Python", "sqatools"]:    result = text[::-1] if len(text) % 4 == 0 else text    print(text, "->", result)
Output
Python -> Python
sqatools -> slootaqs

Line by line

Line 2

“sqatools” has 8 characters, so it is reversed; “Python” has 6, so it is not.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Four copies of the last two characters

Four copies of the last two characters

EasyString Programs · 3 of 106

Write a Python program to make a string of 4 copies of the last two characters of a string (length must be at least 2).

Input
"Python"
Output
onononon

Approach

  1. Slice the last two characters and repeat them with * 4.

Solution

Python
text = "Python"if len(text) >= 2:    print(text[-2:] * 4)else:    print("String must have at least 2 characters")
Output
onononon

Line by line

Line 3

text[-2:] is “on”; multiplying a string repeats it.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Length of the longest string in a list

Length of the longest string in a list

EasyString Programs · 2 of 106

Write a Python program that returns the length of the longest string in a list.

Input
["python", "is", "readable", "fun"]
Output
8 | 8 | readable

Approach

  1. Compare lengths in a loop, or use max() with len.

Solution

Python
words = ["python", "is", "readable", "fun"]longest = 0for w in words:    if len(w) > longest:        longest = len(w)print(longest, "|", max(len(w) for w in words), "|", max(words, key=len))
Output
8 | 8 | readable

Line by line

Lines 3-5

Keep the biggest length seen so far.

Line 6

max(len(w) for w in words) does the same in one line; max(words, key=len) returns the word itself.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

First and last 2 characters

First and last 2 characters

EasyString Programs · 1 of 106

Write a Python program to build a string from the first 2 and the last 2 characters of a string. If the string is shorter than 2 characters, return an empty string.

Input
"Sqatools", "Py", "S"
Output
'Sqatools' -> 'Sqls'
'Py' -> 'PyPy'
'S' -> ''

Approach

  1. Check the length first; then join two slices.

Solution

Python
def ends(text):    if len(text) < 2:        return ""    return text[:2] + text[-2:] for t in ["Sqatools", "Py", "S"]:    print(repr(t), "->", repr(ends(t)))
Output
'Sqatools' -> 'Sqls'
'Py' -> 'PyPy'
'S' -> ''

Line by line

Lines 2-3

Strings shorter than 2 characters return an empty string, as the task asks.

Line 4

text[:2] is the first two characters and text[-2:] the last two.

Note

For “Py” the two slices overlap, so the result is “PyPy”.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs