Your problem is in this line:

userInput.nextLine().charAt(0);

The nextLine() method scans everything on the current line and then advances the pointer past that line. So when you call the charAt() method, you are calling it on the next line, which is blank space, and thus an error is occuring.

Instead, change this line to:

userInput.next().charAt(0)

Note, this means other parts of your code will need changed too.

Edit:

Was about to edit my solution, but @Marc-Andre added his answer which covers it, so just cast your eyes over it too.

Answer from Andrew Martin on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › string index out of range error
r/learnpython on Reddit: String index out of range error
December 21, 2023 -

I'm writing a program that needs to iterate through a string and print the first letter of every word. I have the program working but I can't submit it because of a "String index out of range" error.

An example of what needs to happen is this:

Please type in a sentence: Humpty Dumpty sat on a wall

Output:

H

D

s

o

a

w

Here's my code:

sent = input("Please type in a sentence: ")
index = 0
sent_length = len(sent)
space = " "
print(sent[index])
while index <= sent_length:
    index += 1
    if sent[index] == space:
        print(sent[index + 1])

I'm getting the correct output but it says I have a "string index out of range" error on line 8. I can't figure out what's wrong with it

🌐
Career Karma
careerkarma.com › blog › python › python typeerror: string index out of range solution
Python TypeError: string index out of range Solution | Career Karma
December 1, 2023 - Traceback (most recent call last): File "main.py", line 10, in <module> answer = hamming("Tess1", "Test") File "main.py", line 5, in hamming if a[c] != b[c]: IndexError: string index out of range · Our code returns an error. This is because “a” and “b” are not the same length. “a” has one more character than “b”. This causes our loop to try to find another character in “b” that does not exist even after we’ve searched through all the characters in “b”. We can solve this error by first checking if our strings are valid: def hamming(a, b): differences = 0 if len(a) != len(b): print("Strings must be the same length.") return for c in range(0, len(a)): if a[c] != b[c]: differences += 1 return differences
Discussions

java - StringIndexOutOfBoundsException String index out of range: 0 - Stack Overflow
I am writing a program that opens a text file and checks for comments. It then parses through the comments to check for certain words. The error im having is with the following while loop that che... More on stackoverflow.com
🌐 stackoverflow.com
String index out of range - Oracle Forums
I've got this code written so far for a password validating project, and I've tested it by commenting out different parts, and I only get the string index out of range error when I uncomment this part... More on forums.oracle.com
🌐 forums.oracle.com
October 20, 2008
Found a bug : java.lang.StringIndexOutOfBoundsException: String index out of range: 0 in Http2ServerRequestImpl
Found a bug : java.lang.StringIndexOutOfBoundsException: String index out of range: 0 in Http2ServerRequestImpl#329 More on github.com
🌐 github.com
2
February 8, 2018
Unexpected error: String index out of range: -5 cryptic messages
I'm getting cryptic error messages like: · Unexpected error: String index out of range: -5 java.lang.StringIndexOutOfBoundsException: String index out of range: -5 at java.lang.String.substring(String.java:1967) at XLinkResolver.parseXML(XLinkResolver.java:217) at XLinkResolver.resolveXLi... More on github.com
🌐 github.com
2
December 11, 2019
People also ask

Does StringIndexOutOfBoundsException indicate index corruption?
No. This exception originates from user-supplied code (scripts, plugins, processors), not from Lucene. If the same query fails with no script involved, file an upstream bug report - that is a different class of issue.
🌐
pulse.support
pulse.support › kb › elasticsearch-stringindexoutofboundsexception-string-index-out-of-range
Elasticsearch StringIndexOutOfBoundsException: String index out ...
Does StringIndexOutOfBoundsException cause data loss?
No. The request that triggered it is rejected before any segment is written, so no data is corrupted. Documents already in the index are unaffected. The risk is silent gaps in ingest pipelines that don't fail the whole bulk request - check the failed count in the bulk response.
🌐
pulse.support
pulse.support › kb › elasticsearch-stringindexoutofboundsexception-string-index-out-of-range
Elasticsearch StringIndexOutOfBoundsException: String index out ...
What's the fastest way to diagnose StringIndexOutOfBoundsException in production?
Pulse, the AI DBA for Elasticsearch and OpenSearch, parses the exception stack trace, attributes it to the responsible Painless script, ingest pipeline, or plugin, and surfaces example failing document IDs in one place. It drafts the exact length() guard or pipeline if clause and can apply the change once you approve it, which replaces manual log correlation across coordinating nodes.
🌐
pulse.support
pulse.support › kb › elasticsearch-stringindexoutofboundsexception-string-index-out-of-range
Elasticsearch StringIndexOutOfBoundsException: String index out ...
🌐
Rollbar
rollbar.com › home › how to fix indexerror: string index out of range in python
How to Fix IndexError: string index out of range in Python | Rollbar
This error occurs when an attempt is made to access a character in a string at an index that does not exist in the string. The range of a string in Python is [0, len(str) - 1] , where len(str) is the length of the string.
Published   April 24, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-string-index-out-of-range-how-to-fix-indexerror
Python string index out of range - How to fix IndexError - GeeksforGeeks
July 23, 2025 - For positive index, the range must be within [0, len(string) - 1] and for negative index, rage should be [-len(string), -1]. Combined validation [for both +ve and -ve indexing] can be done with -len(string) <= index < len(string).
Find elsewhere
🌐
Pulse
pulse.support › kb › elasticsearch-stringindexoutofboundsexception-string-index-out-of-range
Elasticsearch StringIndexOutOfBoundsException: String index out of range - Common Causes & Fixes
May 21, 2026 - How to confirm: reindex one offending document with the analyzer disabled to isolate the plugin. Field value containing an unexpected null or empty string after doc[...].value access in a script. How to confirm: add a doc['field'].size() > 0 guard temporarily; if the error disappears, missing values are the cause.
🌐
Coderanch
coderanch.com › t › 372047 › java › string-index-range
string index out of range (Java in General forum at Coderanch)
I am writing this code and getting an error : java.lang.StringIndexOutOfBoundsException: String index out of range: -70. This is my code snippet,Any idea how I solve this one.
🌐
Quora
quora.com › How-do-you-resolve-indexerror-index-out-of-range-0-Python-3-x-development
How to resolve 'indexerror: index out of range: 0' (Python 3.x, development) - Quora
Answer (1 of 3): My best guess is that you are trying to access element[0] where element is an empty list. Take a look at the list you are accessing. E.g. type(element) and len(element) where I am pretending your list is named element. If type(element) is not list then perhaps I’m on the wrong ...
🌐
Codefinity
codefinity.com › courses › v2 › 04fb3c65-4043-4ee3-a995-cba5bdd807af › b427d60d-9690-43e9-8110-556cc8891a2c › 7b6b9d37-e031-4e8d-ac83-ec2f3b893ebb
Learn Indexing and Slicing | Strings
Python uses zero-based indexing, so the first character is at index 0. You can take single characters with indexing and ranges of characters with slicing. Use square brackets with a single position.
🌐
Raymond Camden
raymondcamden.com › 2011 › 02 › 21 › ColdFusion-9-ORM-error-String-index-out-of-range-0
ColdFusion 9 ORM error: String index out of range: 0
My first thought was some kind of simple string error. Perhaps I was doing a left() on a value I assumed had a certain number of characters and for whatever reason the field was blank. However, I narrowed it down to a bit of code that looked like this: <cfset panels = page.getPanels()> <cfloop index="p" array="#panels#"> <cfoutput>#p.getName()#<br/></cfoutput> </cfloop> At first I thought - perhaps one of the objects in the array was null.
🌐
Oracle
forums.oracle.com › ords › apexds › post › string-index-out-of-range-7023
String index out of range - Oracle Forums
October 20, 2008 - I've got this code written so far for a password validating project, and I've tested it by commenting out different parts, and I only get the string index out of range error when I uncomment this part...
🌐
Quora
quora.com › Why-am-I-getting-String-Index-out-of-range
Why am I getting String Index out of range? - Quora
A StringIndexOutOfBoundsException (commonly phrased “String index out of range”) happens when code tries to access a character position that does not exist in the string. Common patterns, reasons, and fixes: ... Java strings are 0-based: valid indices are 0 ..
🌐
Coderanch
coderanch.com › t › 658095 › java › Correct-java-lang-StringIndexOutOfBoundsException-String
How Do I Correct a java.lang.StringIndexOutOfBoundsException: String Index Out of Range 0 [Solved] (Beginning Java forum at Coderanch)
November 19, 2015 - . . . Also I haven't covered anything on the split method yet but I can try and see if I can figure out how to use it from java API. I do find the API a bit difficult to learn I am afraid it is not easy to read. It takes a lot of practice. Look here. Try "\\s+" which means any number greater than 0 ...
🌐
Python Forum
python-forum.io › thread-19567.html
IndexError: string index out of range ?
Hello all, I just start to learn python, working on the chapter of THE BAGELS DEDUCTION GAME. No matter how hard I am, the order just failed. Always showing: Error:Traceback (most recent call last): File '/Users/qiyin/Downloads/Python37/bagels.p...
🌐
GitHub
github.com › Dash-Industry-Forum › DASH-IF-Conformance › issues › 484
String index out of range: -5 cryptic messages · Issue #484
December 11, 2019 - Hi, I'm getting cryptic error messages like: Unexpected error: String index out of range: -5 java.lang.StringIndexOutOfBoundsException: String index out of range: -5 at java.lang.String.substring(String.java:1967) at XLinkResolver.parseX...
Author   Dash-Industry-Forum
🌐
Qlik Community
community.qlik.com › t5 › Talend-Studio › resolved-String-index-out-of-range-error › td-p › 2296474
Solved: [resolved] String index out of range error - Qlik Community - 2296474
November 16, 2024 - In xml file there are some house no values that longer than 40 and i want to cut all the values that are greater than 40. so i try the code below in tMap but i got "java.lang.StringIndexOutOfBoundsException: String index out of range: 40 at java.lang.String.substring(Unknown Source)" error? row4.house_no.length()>40 ?"" : row4.house_no.substring(0,40) Do you have any idea what cause this error, or a better way to take 0-40 character without using tJavaRow.
🌐
Teradata
support.teradata.com › knowledge
- java.lang.StringIndexOutOfBoundsException: String index out of range: 0 - Knowledge Portal
- Analytic Applications - Customer upgraded from CIM 7.1.1.0 to CIM 7.1.1.1 and the communications that worked before started to fail with error: com.teradata.trm.common.workflow.TaskException: java.lang.StringIndexOutOfBoundsException: String index out of range: 0 User created selection criteria from editable attributes, where