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
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.
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.
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.
x = x[:50]
For details on slices like this, refer to the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With