Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

arrays - How can I split a string at the first occurrence of a letter in Python?

A have a series of strings in the following format. Demonstration examples would look like this:

71 1 * abwhf

8 askg

*14 snbsb

00ab

I am attempting to write a Python 3 program that will use a for loop to cycle through each string and split it once at the first occurrence of a letter into a list with two elements.

The output for the strings above would become lists with the following elements:

71 1 * and abwhf

8and askg

*14 and snbsb

00 and ab

There is supposed to be a space after the first string of the first three examples but this only shows in the editor

How can I split the string in this way?

Two posts look of relevance here:

The first answer for the first question allows me to split a string at the first occurrence of a single character but not multiple characters (like all the letters of the alphabet).

The second allows me to split at the first letter, but not just one time. Using this would result in an array with many elements.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The only way I can think of is to write the function yourself:

import string

def split_letters(old_string):
    index = -1
    for i, char in enumerate(old_string):
        if char in string.letters:
            index = i
            break
    else:
        raise ValueError("No letters found") # or return old_string
    return [old_string[:index], old_string[index:]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...