Testing for the first few letters of a string

A

Alexnb

Okay, I have a fix for this problem, but it is messy and I think there might
be a better way. Heres an example:

Lets say I have a string: "My name is alex"

and I have another string "My name is alex, and I like pie".

I want to test to see if just the "My name is alex" part is there. I don't
care about the pie part.
My first instinct was to just create a for loop and test for the string like
this:

n = 0

for x in string1:
if string1[n] == string2[n]
n = n +0
else:
break
and then later testing to see what n was = to and figuring out if it got
through the whole loop. I feel like there should be an easier way to do
this, and probably is. So Does anyone have a suggestion?
 
S

Sean DiZazzo

try

string1 = "My name is alex"
string2 = "My name is alex, and I like pie"

if string2.startswith(string1):
process()

or

if you want to match a set number of characters you can use a slice:

if string2[:15] == string1[:15]:
process()

or

if you dont care where the characters appear in the string, beginning,
middle, end, etc:

if string2 in string1:
process()

Theres lots of other ways as well. http://docs.python.org/lib/string-methods.html

~Sean
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top