DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk1 min

Get the First Character of a Python String Safely

Get the first element of a non-empty Python string with s[0]. Use s[:1] if an empty string should produce an empty result instead of IndexError.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a non-empty Python string s, use s[0]. Python sequences start at index 0, so this returns the first element as a one-character str.

Get the first character with s[0]

s = "Python"
first = s[0]  # "P"

Python strings are indexed from zero: index 0 is the first element, index 1 is the second, and so on. Because Python has no separate character type, indexing a string returns another string of length one. The Python built-in types reference documents that, for a non-empty string, s[0] is equivalent to s[0:1].

As an Amazon Associate I earn from qualifying purchases.

What if the string might be empty?

Indexing an empty string at 0 raises IndexError, because there is no element at that position. Choose the operation that matches the function’s contract:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Expression Non-empty string Empty string Use when
s[0] Returns the first character as a one-character str Raises IndexError An empty string is invalid and should be handled explicitly
s[:1] Returns the first character as a one-character str Returns "" An empty result is acceptable

For example, a slice provides an empty-safe result:

s = ""
first_or_empty = s[:1]  # ""

If an empty value is an error in your application, check for it and raise or handle a clear application-specific error rather than silently returning an empty string.

Does the first element always match one visible character?

Not necessarily. Python str values are immutable sequences of Unicode code points, and s[0] returns one code point. A symbol that appears as a single character on screen can consist of multiple code points, so indexing may return only part of what a person perceives as one character. If an interface must split text into user-perceived characters, use grapheme-aware Unicode processing instead of assuming that s[0] is a complete visual character.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What if the value is bytes?

bytes represents binary data, not decoded text. Its indexing does not return a text str character. Decode the bytes with the correct encoding first, then index the resulting string. Calling str(b"...") without encoding arguments produces the bytes object’s representation; it does not decode the data. See the Python built-in types reference for the distinction.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.