[Tutor] Another string-manipulation question
Mike Hansen
Mike.Hansen at atmel.com
Wed May 9 23:45:01 CEST 2007
> -----Original Message-----
> From: tutor-bounces at python.org
> [mailto:tutor-bounces at python.org] On Behalf Of Alan Gilfoy
> Sent: Wednesday, May 09, 2007 2:42 PM
> To: tutor at python.org
> Subject: [Tutor] Another string-manipulation question
>
> Given a string, how would I?:
>
> 1. Make sure only the first letter string_name[0], is capitalized.
> This would involve using string_name.lower() to lowercase everything
> else, but how do I use .upper(), or some other method, to capitalize
> only the first character?
There's a string method called capitalize, so you can use
string_name.capitalize()
In [27]: x = "rakaNishu"
In [28]: x = x.capitalize()
In [29]: x
Out[29]: 'Rakanishu'
>
> 2. Make sure that there are no symbols (non-letter,
> non-number) in the
> string, and, if one is found, remove it.
>
> Pseudocode time, as to a potential approach-
>
> for each character in the string:
> if character not in
> "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
> remove it
Someone may have a better idea on this one. Off the top of my head, you
can build a new string while checking each character using another
string method isalpha. You might want to check the string first before
even bothering with the loop. i.e. if not string_name.isalpha()...then
enter this loop below...
In [38]: x = "rakan345ishu"
In [39]: newx = ""
In [40]: for chr in x:
....: if chr.isalpha():
....: newx += chr
....:
In [41]: print newx
rakanishu
Mike
More information about the Tutor
mailing list