By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

The same string could describe different byte sequences otherwise. But it is actually a byte sequence that will be encoded by zlib. Learn more. Ask Question. Asked 9 years, 6 months ago.

Active 9 years, 6 months ago. Viewed 9k times. I don't understand in 2. X it worked : import zlib zlib. Regards Bussiere. Compression always works on sequences of bytes, but you need to convert to them first i.

Active Oldest Votes. This is meant to enforce that you actually have a defined encoding. Curious: why does this work for me Python 3. Check the release docs, this change might be enforced in a later version of 3. Wow, and this answer is still helpful. Thanks for posting all those years ago. You are welcome. Isn't it great if your basic implementation details don't change every few years.

In python 2.

python 3 compress string

In python 3.Get the latest tutorials on SysAdmin and open source topics. Write for DigitalOcean You get paid, we donate to tech non-profits.

DigitalOcean Meetups Find and meet other developers in your city. Become an author. List comprehensions offer a succinct way to create lists based on existing lists.

When using list comprehensions, lists can be built by leveraging any iterableincluding strings and tuples. Syntactically, list comprehensions consist of an iterable containing an expression followed by a for clause.

This can be followed by additional for or if clauses, so familiarity with for loops and conditional statements will help you understand list comprehensions better. List comprehensions provide an alternative syntax to creating lists and other sequential data types.

python 3 compress string

While other methods of iteration, such as for loops, can also be used to create lists, list comprehensions may be preferred because they can limit the number of lines used in your program. A list, or other iterable, is assigned to a variable. Additional variables that stand for items within the iterable are constructed around a for clause. The in keyword is used as it is in for loops, to iterate over the iterable. The list we created with the list comprehension is comprised of the items in the string 'shark'that is, one string for each letter.

List comprehensions can be rewritten as for loops, though not every for loop is able to be rewritten as a list comprehension. This may help us better understand how the list comprehension works. When creating a list with a for loop, the variable assigned to the list needs to be initialized with an empty list, as it is in the first line of our code block.

The for loop then iterates over the item, using the variable letter in the iterable string 'shark'. Within the for loop, each item within the string is added to the list with the list. List comprehensions can be rewritten as for loops, and some for loops can be rewritten to be list comprehensions to make code more succinct.

List comprehensions can utilize conditional statements to modify existing lists or other sequential data types when creating new lists. The keywords of for and in are used, as they were in the section aboveand now an if statement is added.Please Login in order to post a comment. The list is built of elements of len list cint k.

From this link : it makes the input a tuple of its elements. Which is why his code prints tuples instead of a list. It would be really helpful I am really facing problem with this thing for a long time. It allows you to pass each element of the list to the print function rather than the list itself.

Compress the String!

One argument is for the data as you mentionedthe other one is for the keyvalue function. Soin this case its taking the data itself as the key value in the form of an identity function when we are not specifying any key values.

I honestly struggled with this example Thank you for your answer, at least I spent time trying to understand it To read more about this function, Check this out. This is a very bad introduction to "groupby " function.

Subscribe to RSS

This omits virtually every aspect of the function that one would need to understand it. I had trouble undetstanding how to write a list comprehension over the output of the groupby function. I have absolutely no clue what's going on here. The challenge gives no explanation of what this function does, and the docs hardly help at all. I don't know anything about how to use this function. We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Practice Compete Jobs Leaderboard. Problem Submissions Leaderboard Discussions Editorial. Sort Discussions, By:. Sure thing. Basically I'm unpacking the list comprehension and printing each element of it.

Encapsulate your code into functions

Hope this helps, let me know if you have any other questions about anything specific. Very nice.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service.

Learn Python - Full Course for Beginners [Tutorial]

Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up.

python 3 compress string

I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. Can someone suggest a better way to do this? This will allow you to test it more easily.

python 3 compress string

You will also be able to return values instead of printing them, this will make the code more reusable:. Counter offers simplified ways of counting elements of an iterable:. You can even simplify further as Counter can take any iterable in its constructor. You can also use str. To me, compressing a string mean having a mean to decompress it back. Using a dictionnary keyed by each letter as you do, you lost an important information: which letter is next to which one. Also 'aabaabaabaa' will be compressed to 'a8b3' which, to me, doesn't make sense and would be better as 'a2b1a2b1a2b1a2'.

But I might be wrong. In this case, itertools. In the itertools module there is the groupby function that groups together runs of the same values. It also has the advantage that it directly iterates over the input, instead of over its indices have a look at Loop like a Native!

This makes it work also for a generator, which does not have a length:. Sign up to join this community. The best answers are voted up and rise to the top. Home Questions Tags Users Unanswered. String compression function in python code [closed] Ask Question. Asked 1 year, 3 months ago.

Active 9 months ago. Viewed 8k times. Peilonrayz Active Oldest Votes. But if you find a nice way to write it as a comprehension that would be nice, I could not think of any. But I only have 3. This makes it work also for a generator, which does not have a length: from itertools import islice, cycle compress islice cycle 'a'10 'a10'.

Graipher Graipher Please explain your reasoning how your solution works and why it is better than the original so that the author and other readers can learn from your thought process.This module provides a simple interface to compress and decompress files just like the GNU programs gzip and gunzip would.

The data compression is provided by the zlib module. The gzip module provides the GzipFile class, as well as the opencompress and decompress convenience functions. The GzipFile class reads and writes gzip -format files, automatically compressing or decompressing the data so that it looks like an ordinary file object. Note that additional file formats which can be decompressed by the gzip and gunzip programs, such as those produced by compress and packare not supported by this module.

Open a gzip-compressed file in binary or text mode, returning a file object. The filename argument can be an actual filename a str or bytes objector an existing file object to read from or write to. The mode argument can be any of 'r''rb''a''ab''w'or 'wb' for binary mode, or 'rt''at'or 'wt' for text mode.

The default is 'rb'. The compresslevel argument is an integer from 0 to 9, as for the GzipFile constructor. For binary mode, this function is equivalent to the GzipFile constructor: GzipFile filename, mode, compresslevel.

In this case, the encodingerrors and newline arguments must not be provided. For text mode, a GzipFile object is created, and wrapped in an io. TextIOWrapper instance with the specified encoding, error handling behavior, and line ending s. Changed in version 3. Constructor for the GzipFile class, which simulates most of the methods of a file objectwith the exception of the truncate method.

At least one of fileobj and filename must be given a non-trivial value. The new class instance is based on fileobjwhich can be a regular file, a io. BytesIO object, or any other object which simulates a file. It defaults to Nonein which case filename is opened to provide a file object. When fileobj is not Nonethe filename argument is only used to be included in the gzip file header, which may include the original filename of the uncompressed file.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service.

The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. I'm making a python "script" that sends a string to a webservice in C. I was thinking of converting it into a file and then compressing the file. But I'm looking for a method to directly compress the string. You can also use sys. Learn more. How to compress or compact a string in Python Ask Question.

Asked 5 years ago. Active 5 years ago. Viewed 8k times. How can I compress or compact the string? Will your web service understand your compressed string? Selcuk That's the idea. My webservice will descompress the string and store it in a database. If is important, the web service is in C. Active Oldest Votes. How about zlib? Is there zlib avalaible in other lenguages? My web service is in C Sorry for not adding that information.Strings are amongst the most popular types in Python.

We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes.

Creating strings is as simple as assigning a value to a variable. Python does not support a character type; these are treated as strings of length one, thus also considered a substring. To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. You can "update" an existing string by re assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether.

Following table is a list of escape or non-printable characters that can be represented with backslash notation. This operator is unique to strings and makes up for the pack of having functions from C's printf family. When the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the "up. Raw strings do not treat the backslash as a special character at all.

Now let's make use of raw string. In Python 3, all strings are represented in Unicode. It is no longer necessary now. Returns a string padded with fillchar with the original string centered to a total of width columns.

Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given. Decodes the string using the codec registered for encoding. Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'. Determines if string or a substring of string if starting index beg and ending index end are given ends with suffix; returns true if so and false otherwise.

Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.

Python 3 - Strings

Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. Returns true if string has at least 1 character and all characters are alphabetic and false otherwise. Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise. Merges concatenates the string representations of elements in sequence seq into a string, with separator string.

Returns a space-padded string with the original string left-justified to a total of width columns. Returns a space-padded string with the original string right-justified to a total of width columns. Splits string according to delimiter str space if not provided and returns list of substrings; split into at most num substrings if given.