Limiting the number of characters in a string in Python

1

I have a Python script that is generating string with many characters and I need each string to create a folder with its name. But do not stick to the problem, because what I really want to know is how to limit that 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

    
asked by anonymous 30.05.2018 / 23:14

2 answers

2

The string type is iterated 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 at the beginning of the text:

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

However, if the value entered after the colon exceeds the text size, it will only be returned to the end of the text:

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

In this way, to limit a text to a number N of characters, just do texto[:N] .

Further Reading:

30.05.2018 / 23:54
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
    
30.05.2018 / 23:45