0

Can anyone help me with the following query what is the pythonic way to cleanse the following strings:

Lets say I have the word

"abcd   

or

'blahblah

then the words actually are

abcd, blahblah

I can think of a basic way.. but actually I am reading a huge text file.. and explicitly writing a code to read char by char seems like overkill and definitely not pythonic.. I am sure there is a pythonic way to do this..:) Thanks

0

2 Answers 2

2

You can strip unwanted characters from the beginning and end of a string using the str.strip() method.

>>> '"abcd'.strip( '"\'' )
'abcd'
>>> '\'blahblah'.strip( '"\'' )
'blahblah'
>>> print( '"abcd'.strip( '"\'' ) )
abcd
>>> print( '\'blahblah'.strip( '"\'' ) )
blahblah
Sign up to request clarification or add additional context in comments.

2 Comments

and how do you strip down the single quotes in the start and the end..? Shouldnt the out put be like abcd and not 'abcd'
No, it’s just in quotes because the return value itself is a string. If you print the value itself, you’ll see that there are no more quotes in the string. Changed my answer to show that.
1

Looks like you want just the alphabetical characters from each word.

import re
_regex = r'\W+' #word characters only    

#read in input
#split input on ' ' (space), to get words

for word in list_of_words:
    word = re.sub(_regex, '', word)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.