What is the best way to create a string array in python?

后端 未结 11 1389
南旧
南旧 2021-02-03 17:45

I\'m relatively new to Python and it\'s libraries and I was wondering how I might create a string array with a preset size. It\'s easy in java but I was wondering how I might do

相关标签:
11条回答
  • 2021-02-03 18:24

    Sometimes I need a empty char array. You cannot do "np.empty(size)" because error will be reported if you fill in char later. Then I usually do something quite clumsy but it is still one way to do it:

    # Suppose you want a size N char array
    charlist = [' ']*N # other preset character is fine as well, like 'x'
    chararray = np.array(charlist)
    # Then you change the content of the array
    chararray[somecondition1] = 'a'
    chararray[somecondition2] = 'b'
    

    The bad part of this is that your array has default values (if you forget to change them).

    0 讨论(0)
  • 2021-02-03 18:28

    In python, you wouldn't normally do what you are trying to do. But, the below code will do it:

    strs = ["" for x in range(size)]
    
    0 讨论(0)
  • 2021-02-03 18:31

    Are you trying to do something like this?

    >>> strs = [s.strip('\(\)') for s in ['some\\', '(list)', 'of', 'strings']]
    >>> strs 
    ['some', 'list', 'of', 'strings']
    
    0 讨论(0)
  • 2021-02-03 18:31
    def _remove_regex(input_text, regex_pattern):
        findregs = re.finditer(regex_pattern, input_text) 
        for i in findregs: 
            input_text = re.sub(i.group().strip(), '', input_text)
        return input_text
    
    regex_pattern = r"\buntil\b|\bcan\b|\bboat\b"
    _remove_regex("row and row and row your boat until you can row no more", regex_pattern)
    

    \w means that it matches word characters, a|b means match either a or b, \b represents a word boundary

    0 讨论(0)
  • 2021-02-03 18:31

    If you want to take input from user here is the code

    If each string is given in new line:

    strs = [input() for i in range(size)]
    

    If the strings are separated by spaces:

    strs = list(input().split())
    
    0 讨论(0)
  • 2021-02-03 18:32

    The simple answer is, "You don't." At the point where you need something to be of fixed length, you're either stuck on old habits or writing for a very specific problem with its own unique set of constraints.

    0 讨论(0)
提交回复
热议问题