473,569 Members | 2,615 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to return an "not string' error in function?

first of all I have to claim that I'm a noob so please help me don't
blame me:)

for example:

def test(s):
if type(s) != ? :
return
#So here I want establish a situation about that if <sis not string
#then <return>, but how should write the <??
#Or is there any other way to do it?

Any suggestion would be appreciate

Peace

Sep 21 '06 #1
11 1741
def test(s):
if type(s) != ? :
return
#So here I want establish a situation about that if <sis not string
#then <return>, but how should write the <??
#Or is there any other way to do it?
>>isinstance("h ello", basestring)
True
>>isinstance(u" hello", basestring)
True

This will return true for both regular strings and for unicode
strings. If that's a problem, you can use
>>import types
isinstance("h ello", types.StringTyp e)
True
>>isinstance(u" hello", types.StringTyp e)
False
>>isinstance("h ello", types.UnicodeTy pe)
False
>>isinstance(u" hello", types.UnicodeTy pe)
True

....or, if you don't want to qualify them with "types." each time,
you can use
>>from types import StringType, UnicodeType
to bring them into the local namespace.

HTH,

-tkc


Sep 21 '06 #2
Thank you so much it answers my humble question perfectly:)

Sep 21 '06 #3
Tim Chase <py*********@ti m.thechases.com wrote:
This will return true for both regular strings and for unicode
strings. If that's a problem, you can use
>import types
isinstance("he llo", types.StringTyp e)
True
>isinstance(u"h ello", types.StringTyp e)
False
>isinstance("he llo", types.UnicodeTy pe)
False
>isinstance(u"h ello", types.UnicodeTy pe)
True

...or, if you don't want to qualify them with "types." each time,
you can use
>from types import StringType, UnicodeType

to bring them into the local namespace.
They already are in the builtin namespace under their more usual names of
str and unicode respectively, so there is no need to import them, just use
them:
>>isinstance("h ello", str)
True

.... etc ...
Sep 21 '06 #4
Or yes that seems a handy way:)

Thanks for all wonderful people here:)

Peace
Duncan Booth wrote:
Tim Chase <py*********@ti m.thechases.com wrote:
This will return true for both regular strings and for unicode
strings. If that's a problem, you can use
>>import types
>>isinstance("h ello", types.StringTyp e)
True
>>isinstance(u" hello", types.StringTyp e)
False
>>isinstance("h ello", types.UnicodeTy pe)
False
>>isinstance(u" hello", types.UnicodeTy pe)
True

...or, if you don't want to qualify them with "types." each time,
you can use
>>from types import StringType, UnicodeType
to bring them into the local namespace.

They already are in the builtin namespace under their more usual names of
str and unicode respectively, so there is no need to import them, just use
them:
>isinstance("he llo", str)
True

... etc ...
Sep 21 '06 #5
In article <11************ *********@k70g2 000cwa.googlegr oups.com>,
<br*********@gm ail.comwrote:
>Thank you so much it answers my humble question perfectly:)
HOWEVER, to answer you final question, yes, there is a different
and, in general, better, way. While there's a lot to say about
good Python style and typing, I'll summarize at a high level:
you shouldn't have to check types. I can understand that you
are working to make a particular function particularly robust,
and are trying to account for a wide range of inputs. This is
healthy. In stylish Python, though, you generally don't need
type checking. How would it be, for example, if someone passed
the number 3 to your function. Is that an error? Do you want
it automatically interpreted as the string "3"? You can achieve
these results withOUT a sequence of

if isinstance(...
elif isinstance(...
...

perhaps with something as simple as

my_input = str(my_input).

One of us will probably follow-up with a reference to a more
detailed write-up of the subject.
Sep 21 '06 #6
Thank you for your inputing which has been great inspirational:)

What I tried to do is to write a string.split() module, so I started
with:

def spilt(a):
l=[]
index=0
if not isinstance(a, basestring): #Or isinstance(a, str)
return
for i in len(a):
if a[i]=' ':
item=a[index:i]
l.append(item)
............... ...

I'm still working on it:)

Thank you again

Peace

PS: Is str() the same as repr() ?

Cameron Laird wrote:
In article <11************ *********@k70g2 000cwa.googlegr oups.com>,
<br*********@gm ail.comwrote:
Thank you so much it answers my humble question perfectly:)

HOWEVER, to answer you final question, yes, there is a different
and, in general, better, way. While there's a lot to say about
good Python style and typing, I'll summarize at a high level:
you shouldn't have to check types. I can understand that you
are working to make a particular function particularly robust,
and are trying to account for a wide range of inputs. This is
healthy. In stylish Python, though, you generally don't need
type checking. How would it be, for example, if someone passed
the number 3 to your function. Is that an error? Do you want
it automatically interpreted as the string "3"? You can achieve
these results withOUT a sequence of

if isinstance(...
elif isinstance(...
...

perhaps with something as simple as

my_input = str(my_input).

One of us will probably follow-up with a reference to a more
detailed write-up of the subject.
Sep 21 '06 #7
br*********@gma il.com wrote:
(OT : please dont top-post)
Thank you for your inputing which has been great inspirational:)

What I tried to do is to write a string.split() module,
So don't waste time:
>>"ab eced f aazaz".split()
['ab', 'eced', 'f', 'aazaz']
>>"ab-eced-ff-aazaz".split('-')
['ab', 'eced', 'ff', 'aazaz']
>>>


--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Sep 21 '06 #8
Thank you for your reminder:)

However I saw the split() function in the first place and that why I'm
trying write one myself:)

Peace

Bruno Desthuilliers wrote:
br*********@gma il.com wrote:
(OT : please dont top-post)
Thank you for your inputing which has been great inspirational:)

What I tried to do is to write a string.split() module,

So don't waste time:
>"ab eced f aazaz".split()
['ab', 'eced', 'f', 'aazaz']
>"ab-eced-ff-aazaz".split('-')
['ab', 'eced', 'ff', 'aazaz']
>>

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Sep 21 '06 #9
br*********@gma il.com wrote:
(please, *stop* top-posting - corrected)
Bruno Desthuilliers wrote:
>>
br*********@gma il.com wrote:
(OT : please dont top-post)
>>What I tried to do is to write a string.split() module,
So don't waste time:
>>>>"ab eced f aazaz".split()
['ab', 'eced', 'f', 'aazaz']
>>>>"ab-eced-ff-aazaz".split('-')
['ab', 'eced', 'ff', 'aazaz']
Thank you for your reminder:)

However I saw the split() function in the first place and that why I'm
trying write one myself:)
Ok. Then if it's for learning, let's have a look :)
def spilt(a):
def split(astring, sep=' '):
l=[]
index=0
if not isinstance(a, basestring): #Or isinstance(a, str)
return
It's an error, so you don't want to pass it silently:

if not isinstance(astr ing, basetring):
raise TypeError('expe cted a string or unicode, got : %s' \
% type(astring)
for i in len(a):
The common idiom is : "for item in sequence:". If you need indexes too,
use enumerate: "for i, char in enumerate(astri ng):".

But anyway, you may want to have a look at str.find() or str.index().
if a[i]=' ':
item=a[index:i]
l.append(item)

Good luck...

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Sep 21 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
2411
by: strout | last post by:
function F(e) { return function(){P(e)} } Can anybody tell me what the code is doing? If return another function all in a function I would do function F(e)
12
4110
by: Jose Fernandez | last post by:
Hello. I'm building a web service and I get this error. NEWS.News.CoverNews(string)': not all code paths return a value This is the WebMethod public SqlDataReader CoverNews(string Sport) {
1
2110
by: Daylor | last post by:
how can i return string to .Net application from c dll ? i have the text in char sText ; and i want to return it from c dll to .Net application. i tried : *char in the function, but the didnt saw the string i passed. what type/way i need to do ?
5
6116
by: krwill | last post by:
I'm trying to automate a combo box to add a record to the source table if it's "Not In List". I've tried many different examples and none have worked. Combo Box Name = Combo24 Source Table Name = TblHandler Source Field Name = HandlerLoginID (key column = HandlerID which is an autonumber) Thanks
8
3276
by: John Nagle | last post by:
Here's a wierd problem: I have a little test case for M2Crypto, which just opens up SSL connections to web servers and reads their certificates. This works fine. But if I execute socket.setdefaulttimeout(5.0) so that the sockets don't wait too long if there's no SSL server, I get
13
3645
by: arnuld | last post by:
/* C++ Primer 4/e * section 3.2 - String Standard Library * exercise 3.10 * STATEMENT * write a programme to strip the punctation from the string. */ #include <iostream> #include <string>
4
9048
by: jk2l | last post by:
Error 10 error LNK2019: unresolved external symbol __imp__glBindTexture@8 referenced in function "public: void __thiscall GLTexture::Use(void)" (?Use@GLTexture@@QAEXXZ) GLTexture.obj Error 11 error LNK2019: unresolved external symbol __imp__glEnable@4 referenced in function "public: void __thiscall GLTexture::Use(void)"...
11
12893
by: askalottaqs | last post by:
i created a function which u send a string, and it tokenizes according to spaces, so i send it a string for it to return me a string array, but on the declaration of the function it says error C2470: 'splitter' : looks like a function definition, but there is no parameter list; skipping apparent body and error C2092: 'splitter' array...
4
1818
by: lostlander | last post by:
In ARMCC, and Microsoft C, when i use a function which is never defined or delared, it gives out a warning, not a compiling error? why? (This leads to a bug to my program since I seldom pay much attention to warnings...) Thanks for explanation!
0
7935
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8144
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7692
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7992
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5244
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3677
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3666
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2128
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1235
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.