Testing for the first few letters of a string
Sean DiZazzo
half.italian at gmail.com
Thu Aug 7 11:51:00 EDT 2008
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
On Aug 7, 8:40 am, Alexnb <alexnbr... at gmail.com> wrote:
> 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?
> --
> View this message in context:http://www.nabble.com/Testing-for-the-first-few-letters-of-a-string-t...
> Sent from the Python - python-list mailing list archive at Nabble.com.
More information about the Python-list
mailing list