1

I am wondering how I can implement a string check, where I want to make sure that the first (&last) character of the string is alphanumeric. I am aware of the isalnum, but how do I use this to implement this check/substitution?

So, I have a string like so:

st="-jkkujkl-ghjkjhkj*"

and I would want back:

st="jkkujkl-ghjkjhkj"

Thanks..

n.y
  • 3,343
  • 3
  • 35
  • 54
AJW
  • 5,569
  • 10
  • 44
  • 57

6 Answers6

5

Though not exactly what you want, but using str.strip should serve your purpose

import string

st.strip(string.punctuation)
Out[174]: 'jkkujkl-ghjkjhkj'
Abhijit
  • 62,056
  • 18
  • 131
  • 204
2

You could use regex like shown below:

import re
# \W is a set of all special chars, and also include '_'
# If you have elements in the set [\W_] at start and end, replace with ''
p = re.compile(r'^[\W_]+|[\W_]+$') 
st="-jkkujkl-ghjkjhkj*"
print p.subn('', st)[0]

Output: jkkujkl-ghjkjhkj

Edit:

If your special chars are in the set: !"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~

@Abhijit's answer is much simpler and cleaner.

If you are not sure then this regex version is better.

sisanared
  • 4,175
  • 2
  • 27
  • 42
1

You can use following two expressions:

st = re.sub('^\W*', '', st)
st = re.sub('\W*$', '', st)

This will strip all non alpha chars of the beginning and the end of the string, not just the first ones.

Fejs
  • 2,734
  • 3
  • 21
  • 40
0

You could use a regular expression.

Something like this could work;

\w.+?\w

However I'm don't know how to do a regexp match in python..

Koen.
  • 25,449
  • 7
  • 83
  • 78
0

hint 1: ord() can covert a letter to a character number

hint 2: alpha charterers are between 97 and 122 in ord()

hint 3: st[0] will return the first letter in string st[-1] will return the last

Whud
  • 714
  • 1
  • 6
  • 19
0

An exact answer to your question may be the following:

def stringCheck(astring):
    firstChar = astring[0] if astring[0].isalnum() else ''
    lastChar = astring[-1] if astring[-1].isalnum() else ''
    return firstChar + astring[1:-1] + lastChar