Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to keep only first 50 char of a string

Tags:

python

string

I have a string which

x = "very_long_string_more_than_50_char_long"

I want to keep only first 50 char and delete the rest. how would i do that?

thanks

like image 601
Sunny Avatar asked Sep 30 '11 12:09

Sunny


People also ask

How do I limit characters in a string in Python?

Use a formatted string literal to format a string and limit its length, e.g. result = f'{my_str:5.5}' . You can use expressions in f-strings to limit the string's length to a given number of characters.

How do I print the first 100 characters of a string in Python?

Method 4: Using slice() Function Pass 100 as an argument to the slice() function as we require 100 characters. Get the first 100 characters of the input string using the slice count value and create a variable to store it. Print the resultant string which contains the first 100 characters of the input string.

How do you isolate part of a string in Python?

You can extract a substring in the range start <= x < stop with [start:step] . If start is omitted, the range is from the beginning, and if end is omitted, the range is to the end. You can also use negative values. If start > end , no error is raised and an empty character '' is extracted.


1 Answers

x = x[:50]

For details on slices like this, refer to the documentation.

like image 188
phihag Avatar answered Nov 06 '22 21:11

phihag