简体   繁体   中英

How to detect string initial in python?

For example I have a string:

"Hello My name is Ralph"

is there any way I could detect HM ni R ?

try :

myText = "Hello My name is Ralph"
print [x[0] for x in myText.split()]

If you wanted to do this with a regex, this would work:

re.findall(r'\b(\w)\w*\b',MY_STRING)

How this works:

\\b is a word boundary. You can check for a word in regex by using \\bWord\\b , and it will return a match for Word

(\\w) This is a group, matching a single letter. Since this is the only group, this is what is returned as the "match" by the regex

\\w* This searches for additional letters in a row, of any length or no length. You didn't include any punctuation, but if you wanted the regex to not break on apostrophes you could change this to something like [\\w\\']* instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM