[PYTHON] 11. Replace tabs with spaces

11. Replace tabs with spaces

Replace each tab character with one space character. Use the sed command, tr command, or expand command for confirmation.

Go

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	//Specify the read file
	name := "../hightemp.txt"

	//Open the file to read
	f, err := os.Open(name)
	if err != nil {
		fmt.Printf("os.Open: %#v\n",err)
		return
	}
	defer f.Close() //Crease at the end

	//Create a scanner library
	scanner := bufio.NewScanner(f)

	//Read one line of data
	for scanner.Scan() {
		//Replace TAB with blank
		fmt.Println(strings.Replace(scanner.Text(),"\t"," ",-1))
	}

	//Check if there was an error
	if err = scanner.Err(); err != nil {
		fmt.Printf("scanner.Err: %#v\n",err)
		return
	}
}

python

#Open file
with open("../hightemp.txt", "r") as f:
    #Read line by line
    for data in f:
        #Replace TAB with whitespace (strip removes white space)
        print(data.strip().replace("\t"," "))

Javascript

//Module loading
var fs = require("fs");
var readline = require("readline");

//Create a stream
var stream = fs.createReadStream("../hightemp.txt", "utf8");

//Pass Stream to readline
var reader = readline.createInterface({ input: stream });

//Row read callback
reader.on("line", (data) => {
    //Convert TAB to whitespace (string"\t"Specify with a regular expression because it does not work well with the specification)
    console.log(data.replace(/\t/g," "))
});

Summary

Is it possible to specify "\ t" in the replacement source string in Javascript? I am surprised again by the small number of Python code.

Top

Recommended Posts

11. Replace tabs with spaces
Replace printf later with LD_PRELOAD
Replace dictionary value with Python> update ()
Replace all at once with sed
Replace non-ASCII with regular expressions in Python
Replace column names / values with pandas dataframe
Fastly replace image colors with PIL / Pillow