Working with Text (Strings)
A lot of programming is about text: names in a form, messages in a chat app, addresses on a parcel, the words in a search box. In code, text is stored as a string, and both Python and JavaScript come with many tools for cleaning, searching and cutting strings.
In this lesson you will read single characters from a string, change its case, remove extra spaces, search inside it, cut out pieces, split it into a list and join lists back into text.
A string is a sequence of characters
A string is an ordered sequence of characters: letters, digits, spaces and symbols. Like a list, each character has an index starting at 0, and you can count them:
name = "Ananya Iyer"
print(len(name))
print(name[0])
print(name[7])
print(name[-1])11 A I r
const name = "Ananya Iyer";
console.log(name.length);
console.log(name[0]);
console.log(name[7]);
console.log(name.at(-1));11 A I r
The space in the middle is a character too, at index 6, which is why "I" is at index 7. JavaScript's at(-1) counts from the end, like Python's name[-1].
Changing case and trimming spaces
People type names in all sorts of ways: "PUNE", "pune", " Pune ". Before you compare or store text, it helps to clean it.
| Job | Python | JavaScript |
|---|---|---|
| All capitals | s.upper() | s.toUpperCase() |
| All small letters | s.lower() | s.toLowerCase() |
| Remove spaces at both ends | s.strip() | s.trim() |
| Capitalise each word | s.title() | no built-in method |
typed = " pUNe "
clean = typed.strip().lower()
print(f"[{typed}]")
print(f"[{clean}]")
print(clean == "pune")
print(clean.title())[ pUNe ] [pune] True Pune
The square brackets in the output show exactly where the spaces were. After cleaning, the typed text matches "pune", and title() gives it a capital first letter for display.
Strings can never be changed in place; they are immutable. Methods like strip() and lower() give you a new string and leave the original alone. That is why the result is stored in clean. Writing typed.strip() on its own line does nothing useful, because the new string is thrown away.
Searching inside a string
You can ask whether a string contains some text, where it is, and how many times it appears:
message = "Your OTP is 4821. Never share your OTP with anyone."
print("OTP" in message)
print(message.count("OTP"))
print(message.find("4821"))
print(message.startswith("Your"))
print(message.replace("OTP", "code"))True 2 12 True Your code is 4821. Never share your code with anyone.
const message = "Your OTP is 4821. Never share your OTP with anyone.";
console.log(message.includes("OTP"));
console.log(message.indexOf("4821"));
console.log(message.startsWith("Your"));
console.log(message.replaceAll("OTP", "code"));true 12 true Your code is 4821. Never share your code with anyone.
find() and indexOf() give the index where the text starts, or -1 if it is not there. Searches are case-sensitive: "otp" in message is False. Use lower() on both sides if case should not matter. In JavaScript, replace() changes only the first match, so use replaceAll() to change every one.
Cutting out pieces: slicing
A slice takes part of a string, from a start index up to, but not including, an end index. Vehicle numbers in India start with a state code and a district number, so slicing can split them up:
number = "HR12AB3456"
print("State code:", number[0:2])
print("District:", number[2:4])
print("Last four:", number[-4:])State code: HR District: 12 Last four: 3456
In JavaScript, use slice(): number.slice(0, 2) gives "HR", and number.slice(-4) gives "3456". Leaving out the end, as in number[-4:], means "to the end of the string".
Splitting and joining
split() breaks a string into a list wherever a separator appears. join() does the opposite: it glues a list of strings together with a separator between them.
route = "Rohtak,Delhi,Jaipur,Ahmedabad"
stops = route.split(",")
print(stops)
print(len(stops), "stops")
print(" -> ".join(stops))['Rohtak', 'Delhi', 'Jaipur', 'Ahmedabad'] 4 stops Rohtak -> Delhi -> Jaipur -> Ahmedabad
JavaScript writes the join the other way round: stops.join(" -> "), with the list first. Splitting is how programs read data such as CSV files, where each line has values separated by commas.
Advanced: going through each character
A loop over a string visits one character at a time. This counts the vowels in a long city name:
city = "Thiruvananthapuram"
vowels = 0
for ch in city.lower():
if ch in "aeiou":
vowels += 1
print(f"{city} has {len(city)} letters and {vowels} vowels")Thiruvananthapuram has 18 letters and 7 vowels
ch in "aeiou" checks whether the character is one of the five vowels. The same loop in JavaScript is for (const ch of city.toLowerCase()), with "aeiou".includes(ch) as the check.
Common mistakes
- Expecting a method to change the string.
name.upper()alone does nothing lasting. Store the result:name = name.upper(). - Comparing without cleaning.
"Pune " == "Pune"is false because of the space. Strip and lower-case input before comparing. - Off-by-one in slices.
s[0:2]gives two characters, indexes 0 and 1. The end index is not included. - Using
replace()in JavaScript for every match. It only replaces the first one; usereplaceAll().
Key points
- A string is a sequence of characters with indexes starting at 0; use
len(s)ors.lengthto count them. - Clean text with
strip()/trim()andlower()/toLowerCase()before comparing it. - Strings are immutable: methods return new strings, so store the result.
- Search with
in/includes(),find()/indexOf()andstartswith()/startsWith(). - Slice with
s[start:end]in Python ors.slice(start, end)in JavaScript; the end is not included. split()turns a string into a list;join()turns a list back into a string.
Exercise
A form gives you the name " kabir singh rathore ". Write a program that removes the extra spaces, prints the name with each word capitalised (Kabir Singh Rathore), and prints the initials with dots (K.S.R.). Use split() and a loop for the initials. Python is enough; try JavaScript too if you like (it has no title(), so capitalise each word yourself).
Show solution
raw = " kabir singh rathore "
clean = raw.strip().title()
initials = ""
for word in clean.split():
initials += word[0] + "."
print(clean)
print(initials)Kabir Singh Rathore K.S.R.
const raw = " kabir singh rathore ";
const words = raw.trim().split(" ");
const capitalised = [];
let initials = "";
for (const word of words) {
const first = word[0].toUpperCase();
capitalised.push(first + word.slice(1));
initials += first + ".";
}
console.log(capitalised.join(" "));
console.log(initials);Kabir Singh Rathore K.S.R.
Stripping first removes the spaces at the ends. Splitting gives one word at a time, and the first character of each word (word[0]) builds the initials.
Quick Quiz
1. What is len("Rohtak")?
There are six characters: R, o, h, t, a, k.
2. After city = " Kochi " and city.strip() on its own line, what is city?
strip() returns a new string; you must store it, as in city = city.strip().
3. What does "HR12AB3456"[2:4] give?
The slice starts at index 2 and stops before index 4.
4. What does "a,b,c".split(",") give in Python?
split(",") breaks the string at each comma and returns a list of strings.
Learn Intro to Programming with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
