Limiting the number of characters in a Python string

Asked

Viewed 7,328 times

1

Guys, I have a Python script that during the processing of information is generating string with many characters and I need each string to create a folder with its "name". But don’t get caught in the problem, because what I really want to know is how do I limit such a string to a desired size and store it in a variable. For example:

stringGrande = "gerando string com muitos caracteres e preciso de cada"
stringPequena = stringGrande (limitada)
print stringPequena

Resultado: gerando string com muitos

for example

2 answers

3


The guy string is iterable in Python and allows you to access its content via Slices. For example, texto[1:5] would return from the first to the fourth character of texto.

>>> print('anderson'[1:5])
nder

If you omit the first value, Python will understand that it is zero, starting from the beginning of the text:

>>> print('anderson'[:5])
ander

Already, if the value reported after the two points exceeds the text size, it will be returned only until the end of the same:

>>> print('anderson'[1:30])
nderson

Thus, to limit a text to a number N character, just do texto[:N].

Additional reading:

2

stringGrande = "gerando string com muitos caracteres e preciso de cada"


def diminuir(str):
    max = 10 # Numero Maximo de caracteres Permitidos.
    if len(str) > max:
        return str[:max]
    else:
        return str


stringPequena = diminuir(stringGrande)
print stringPequena

Browser other questions tagged

You are not signed in. Login or sign up in order to post.