A string in coding is a sequence of characters that a program treats as one piece of text, such as "Hello", a username or a file path. You write it between quotation marks, and the language gives you operations to join, search, slice and compare it.
The idea is the same everywhere, but the details differ by language: how long a string is, whether you can edit it in place, and how emoji count. This article covers the definition, the common operations, and those differences, with examples from Python, JavaScript and Java.
What is a string, exactly?
A string is an ordered list of characters. Order matters: "stop" and "pots" contain the same letters but are different strings. Anything you can type can be part of a string, including spaces, digits, punctuation and symbols.
The quotation marks are not part of the string. They tell the compiler where the text starts and ends. The text Hello without quotes would be read as a name (a variable or a function), not as text.
greeting = "Hello, world" # Python
const greeting = "Hello, world"; // JavaScript
String greeting = "Hello, world"; // Java
Each of these creates a string of 12 characters: five letters, a comma, a space, and five more letters.
Strings versus numbers
A string that looks like a number is still text. "42" holds the characters 4 and 2, and 42 without quotes is a number. The two behave differently:
print("4" + "2") # 42 (joins the text)
print(4 + 2) # 6 (adds the numbers)
print(int("42") + 1) # 43 (convert first, then add)
The first line prints the text 42 because + on two strings joins them. A very common beginner bug is reading a value from a form or a file, which arrives as a string, and forgetting to convert it before doing arithmetic.
How to write a string
Quoting rules vary by language. The Python documentation lists three forms: single quotes, double quotes, and triple quotes. Single and double quotes are interchangeable, which lets one kind contain the other without extra work. Triple-quoted strings can span several lines, and all the whitespace inside is kept.
'allows embedded "double" quotes'
"allows embedded 'single' quotes"
"""first line
second line"""
MDN documents a third style for JavaScript: backticks, which make a template literal. JavaScript treats all three quote styles as string primitives. Java is stricter. Double quotes make a string, and single quotes are reserved for a single char, so 'a' and "a" are different types in Java.
To put a quote character or a line break inside a string, use an escape sequence that starts with a backslash: \" for a double quote, \n for a new line, \\ for a backslash itself. Python's f-strings are a related feature that embeds values directly into the text.
What you can do with a string
Most languages offer the same core operations under different names.
| Operation | Python | JavaScript | Java |
|---|---|---|---|
| Length | len(s) | s.length | s.length() |
| Join | s + t | s + t | s + t |
| Upper case | s.upper() | s.toUpperCase() | s.toUpperCase() |
| First character | s[0] | s[0] | s.charAt(0) |
| Contains | "lo" in s | s.includes("lo") | s.contains("lo") |
Positions in a string are called indexes, and they start at 0. In "Hello", index 0 is H and index 4 is o. Taking a piece of a string by index range is called slicing; the Python version is covered in slicing lists and strings. Splitting a string into parts at a separator is covered in Python string split examples.
Strings are usually immutable
The Python documentation calls strings "immutable sequences of Unicode code points". The Java documentation says the same thing in other words: "Strings are constant; their values cannot be changed after they are created." Immutable means you cannot change a character in place. Operations that look like edits build a new string.
name = "cat"
name[0] = "b" # TypeError: 'str' object does not support item assignment
name = "b" + name[1:] # builds a new string, "bat", and rebinds the name
The second line fails with a TypeError in Python. The third line works because it creates a new string instead of editing the old one. Java behaves the same way, and Java documents the benefit: because strings cannot change, they can be shared safely. C is the notable exception, where a string is a modifiable array of bytes, as explained in strings in C. The same immutability explains why reversing a string in Java always produces a second string.
How a computer stores a string
Computers store numbers, so each character is mapped to a number by a character set. Unicode assigns a number, called a code point, to each character. An encoding then decides how those numbers are turned into bytes. The three common encodings are UTF-8, UTF-16 and UTF-32.
The languages differ in what they expose:
- Python strings are sequences of Unicode code points, so
len("๐")is 1. - JavaScript strings are, in MDN's words, "sequences of UTF-16 code units". Characters outside the Basic Multilingual Plane take two code units (a surrogate pair), so
"๐".lengthis 2. - Java also uses UTF-16. Its documentation says "a supplementary character uses two positions in a String", so
"๐".length()is 2 as well.
The same banana is one character to a person, one unit in Python, and two in JavaScript and Java. In UTF-8 that emoji takes 4 bytes. When you need the number of bytes, for a database column limit or a network message, encode the string first and measure the result, for example len("๐".encode("utf-8")) in Python gives 4. MDN also warns that even code point iteration is not the same as counting what a reader sees: some visible symbols, such as flags and family emoji, are built from several code points, and counting them takes custom code.
Strings with no separate character type
Python has no character type. The documentation says "indexing a string produces strings of length 1", so "cat"[0] is the string "c", and "cat"[0] == "cat"[0:1] is true. JavaScript works the same way. Java and C do have a char type, which is why Java needs both charAt and the string methods.
The empty string and missing values
An empty string, written "", has length 0 and is a perfectly good string. It is not the same as None in Python or null in JavaScript and Java, which mean "no value at all". Calling len(None) in Python raises an error, while len("") returns 0. Many bugs come from a form field that is empty being handled as if it were missing, or the other way round. Decide which one your code means and check for it explicitly.
Comparing and joining strings
Comparing strings is not the same in every language. Python's == compares the text, so "abc" == "abc" is true. In Java, == on two strings compares whether they are the same object, and you should call equals to compare the text. In C, == compares addresses, and you call strcmp.
Joining with + is fine for a few pieces. Inside a loop it creates a new string on every pass, because strings are immutable. Languages offer a better route: "".join(parts) in Python, parts.join("") in JavaScript, and StringBuilder in Java. The Java documentation names StringBuilder among the ways the compiler may implement the + operator, and the same page notes that string buffers support mutable strings.
Common string mistakes
- Forgetting to convert. Input from users and files arrives as text. Convert to a number before adding.
- Off-by-one indexes. The first character is at index 0, and the last is at length minus 1.
- Trying to edit in place. In Python and Java, build a new string instead.
- Mismatched quotes. A string that starts with
"must end with", and a quote inside it needs an escape or the other quote style. - Counting characters with the wrong unit. Bytes, UTF-16 units and code points give different numbers for the same text once it contains emoji or many non-English characters.
If you are just starting out, practice with three things in your language of choice: print a string, print its length, and print its first and last character. Those cover quoting, measuring and indexing, and nearly every other string operation builds on them.
Frequently asked questions
- What is a string in coding, in one sentence?
- A string is a piece of text stored as an ordered sequence of characters, such as a name, a sentence or a file path. Programming languages write it between quotation marks and provide operations to join, search, slice and compare it.
- Is a number in quotes a string?
- Yes. In most languages "42" is a string made of the characters 4 and 2, not the number forty-two. You cannot do arithmetic with it until you convert it to a number, for example with int("42") in Python.
- What is an empty string?
- An empty string is a string with zero characters, written "" in most languages. It is a valid value, and it is different from a missing value such as null or None, which means there is no string at all.
- What does it mean that strings are immutable?
- It means a string cannot be changed after it is created. Python and Java both work this way. Operations that look like edits, such as upper-casing, return a new string and leave the original untouched.
- Does a character count as a string?
- In Python and JavaScript there is no separate character type: a single character is just a string of length 1. In Java and C, a character is its own type (char), and a string is a different thing.