Analyzing string input until it reaches a certain letter on Python

anu_clarset picture anu_clarset · Nov 17, 2011 · Viewed 88.2k times · Source

I need help in trying to write a certain part of a program. The idea is that a person would input a bunch of gibberish and the program will read it till it reaches an "!" (exclamation mark) so for example:

input("Type something: ")

Person types: wolfdo65gtornado!salmontiger223

If I ask the program to print the input it should only print wolfdo65gtornado and cut anything once it reaches the "!" The rest of the program is analyzing and counting the letters, but those part I already know how to do. I just need help with the first part. I been trying to look through the book but it seems I'm missing something.

I'm thinking, maybe utilizing a for loop and then placing restriction on it but I can't figure out how to make the random imputed string input be analyzed for a certain character and then get rid of the rest.

If you could help, I'll truly appreciate it. Thanks!

Answer

Michael Hoffman picture Michael Hoffman · Nov 17, 2011

The built-in str.partition() method will do this for you. Unlike str.split() it won't bother to cut the rest of the str into different strs.

text = raw_input("Type something:")
left_text = text.partition("!")[0]