Skip to content
Advertisement

Tag: string

Python split string in moving window

I have a string with digits like so – digit = “7316717” Now I want to split the string in such a way that the output is a moving window of 3 digits at a time. So I get – [“731”, “316”, “167”, “671”, “717”] How would the approach be? Straightforward way is to put in for-loop and iterate. But

Best way to convert string to bytes in Python 3?

TypeError: ‘str’ does not support the buffer interface suggests two possible methods to convert a string to bytes: Which method is more Pythonic? Answer If you look at the docs for bytes, it points you to bytearray: bytearray([source[, encoding[, errors]]]) Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <=

What is the difference between a string and a byte string?

I am working with a library which returns a “byte string” (bytes) and I need to convert this to a string. Is there actually a difference between those two things? How are they related, and how can I do the conversion? Answer Assuming Python 3 (in Python 2, this difference is a little less well-defined) – a string is a

Joining pairs of elements of a list [duplicate]

This question already has answers here: How to iterate over a list in chunks (39 answers) Closed 8 months ago. I know that a list can be joined to make one long string as in: Obviously this would output: However, what I am trying to do is simply join the first and second strings in the list, then join the

Can you have variables within triple quotes? If so, how?

This is probably a very simple question for some, but it has me stumped. Can you use variables within python’s triple-quotes? In the following example, how do use variables in the text: I would like it to result in: If not what is the best way to handle large chunks of text where you need a couple variables, and there

Titlecasing a string with exceptions

Is there a standard way in Python to titlecase a string (i.e. words start with uppercase characters, all remaining cased characters have lowercase) but leaving articles like and, in, and of lowercased? Answer There are a few problems with this. If you use split and join, some white space characters will be ignored. The built-in capitalize and title methods do

How to insert a character after every 2 characters in a string

Is there a pythonic way to insert an element into every 2nd element in a string? I have a string: ‘aabbccdd’ and I want the end result to be ‘aa-bb-cc-dd’. I am not sure how I would go about doing that. Answer Assume the string’s length is always an even number, The t can also be eliminated with The algorithm

Advertisement