55455

Python 3.4- Inserting spaces at regular intervals [duplicate]

<div class="question-status question-originals-of-duplicate">

This question already has an answer here:

    <li> Split a string into N equal parts? [duplicate] <span class="question-originals-answer-count"> 6 answers </span> </li> </ul>

    I am trying to get Python to allow me to insert a space at regular intervals (every 5th character), in a string. This is my code:

    str1 = "abcdefghijklmnopqrstuvwxyz" list1 = [] list2 = [] count = 3 space = " " # converting string to list for i in str1: list1.append(i) print(list1) # inserting spaces for i in list1: mod = count%6 count = count + 1 if mod == 0: list1.insert(count,space) count = count + 1 #converting back to a string list2 = "".join(list1) print(str(list2))

    however it groups the first section together as 7. Can anyone help me fix this?

    Answer1:

    Very easy with a regex:

    >>> import re >>> ' '.join(re.findall(r'.{1,5}', str1)) 'abcde fghij klmno pqrst uvwxy z'

    Or use a slice:

    >>> n=5 >>> ' '.join([str1[i:i+n] for i in range(0, len(str1), n)]) 'abcde fghij klmno pqrst uvwxy z'

    Answer2:

    In a step by step script:

    You can use the string module to get all the ascii letters in lowercase:

    from string import ascii_lowercase

    Now, you can iterate every five characters and add a space using the following:

    result = "" for i in range(0,len(ascii_lowercase), 5): result += ascii_lowercase[i:i+5] + ' ' print(result)

    Prints the following result:

    abcde fghij klmno pqrst uvwxy z

Recommend

  • Loop and read through multiple sheets of same worksheet and save as individual dataframe/variable [c
  • Use of colon in variable declaration [duplicate]
  • how much time does grid.py take to run?
  • SQL Regex get phone number
  • gcc: Not able to create .so from object files
  • Enable drop just for specific targets in Swing
  • Android listview array adapter selected
  • How do I (de)serialize a serializable dictionary with string array values?
  • SQL - Find duplicate values and remove in a field
  • Find generic sub-lists within a list
  • jquery - how to CUT LI elements from one UL to another UL
  • Conflicting Types Error
  • How to detect if user Did not allow location update
  • Difference between two particular dates [duplicate]
  • JsonConvert.DeserializeObject, Index was outside the bounds of the array
  • Multiple for loop iterators to unpack in Python [duplicate]
  • Bokeh 0.7.1: Dynamically Add Plot to Bokeh-Server Generated Existing Page
  • Upgrade to g++ 4.7 (with c++11 support): any ABI incompatibility?
  • I can't get setInterval() to work in Javascript
  • Adding a new element into the DOM with angularjs does not initiate it
  • creating instance of object using reflection , when the constructor takes an array of strings as arg
  • Jquery UI Sortable, move item automatically
  • Most efficient way to replace lowest list values in dataframe in R
  • List comprehension with if conditional to get list of files of a specific type
  • Alamofire and Reachability.swift not working on xCode8-beta5
  • passing a default argument to a browserify module
  • vectorized indexing/slicing in numpy/scipy?
  • Add dynamic data to line chart from mysql database with highcharts
  • Implementing “partial void” in VB
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • Using Sax parsing to edit and write XML in VB6
  • Run multiple queries from 1 SQL file showing result in multiple tables
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • What's the purpose of QString?
  • wxPython: displaying multiple widgets in same frame
  • Django: Count of Group Elements
  • Sending data from AppleScript to FileMaker records
  • MySQL WHERE-condition in procedure ignored
  • How to delete a row from a dynamic generate table using jquery?
  • Is there any way to bind data to data.frame by some index?