carriage return in python 3.4 does not move to the left - python-3.4

When I use a carriage return in idle nothing seems to happen.
>>>print('2\r3')
23
>>> carriage_return = "I will use a carriage\rreturn"
>>> print(carriage_return)
I will use a carriagereturn
if i run the same lines through the command line it works fine.
>>>print('2\r3')
3
Is this an idle bug (and if so is there a work around) or am i missing something simple? My os is windows 7.

On windows you will have to do a "new line" \n before you do a "carriage return" \r
Example:
>>>car = "carriage\n\rreturn"
>>>print (car)
carriage
return
>>>
[EDIT based on comments]
if the goal is to print over the previous line, the following can be used on Microsoft Windows
import sys
def print_and_return(string):
#adding '\b' which moves the carriage back one character
#based on length of the string
sys.stdout.write(string.ljust(len(string)*2,'\b'))
sys.stdout.flush()
#this will print to stdout, and 'return' position to start
print_and_return("string1")
#normal print, but starting at the start of the previous print
print("string2")
This will produce
string2
And will have overwritten the original string, you can put a time.sleep() between the two statements if you like to witness it.
However this will print over the first line, on the original line, but it will not delete the previous printed string, so if the second string is shorter than the originally printed string, the end of the originally printed string remains on screen.
print_and_return("string1=long")
print("string2")
will produce
string2=long
You can always return the length of the previous string, then add spaces to the end of the second string, which will then overwrite the additional characters with spaces.
import sys
def print_and_return(string):
sys.stdout.write(string.ljust(len(string)*2,"\b"))
sys.stdout.flush()
return len(string)
l = print_and_return("string1=long")
#normal print, but starting at the start of the previous print
#adding spaces to ensure the length is the same as previous printed string
print("string2".ljust(l))
this will now produce:
string2
HTH.

Related

Having problems with accessing files on a mapped network drive, using pywin32 client

I am currently using the following code to open up a word document (and then save it but that is irrelevant to opening the file at the moment):
word=win32.Dispatch('Word.Application')
try:
doc = word.Documents.Open('S:\problem\file.docx')
except Exception as e:
print(e)
(-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'Sorry, we
couldn’t find your file. Is it possible it was moved, renamed or
deleted?\r (S:\\problem\\file.docx)',
'wdmain11.chm', 24654, -2146823114), None)
The "problem" directory is the only directory it seems the win32 client is not able to recognize. I have renamed it several times to even single letters to see if the naming was the problem for some reason, but that does not seem to be the problem.
The file path is also recognized by the docx function- docx.Document and it is able to read the files in the directory. Here is the same code and results for the docx snippet:
Document('S://problem/file.docx')
<docx.document.Document at 0x83d3c18>
In Python strings, bkslash ("\") is one of the characters with a special meaning: it's used to create escape sequences (special chars) together with the char that follows it (this comes from C). Here's what [Python 3]: String and Bytes literals states:
The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
In your string, you have "\p" (which is OK) and "\f" which is interpreted as a single char (form feed - new page), making your path invalid.
In order to fix this, either:
Escape (double) any "\" in the string (well, this is just a precaution measure since you only have to escape the ones that produce an escape sequence - in our example, "\p" is perfectly fine), except the ones that you want to produce an escape sequence: 'S:\problem\file.docx'
Make the string raw, by prepending it with the r marker (note that if the string ends with a "\", that should still be escaped, otherwise it will escape the string ending marker (' or ") that comes after it, yielding SyntaxError): r'S:\problem\file.docx'
As a general rule, in order to ensure that strings are what you think they are, either:
Check their length: if it's smaller than the number of chars you see (in the code), it means that there is at least one escape sequence
Use repr
Example:
>>> import sys
>>> sys.version
'3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)]'
>>>
>>> s0 = 'S:\problem\file.docx'
>>> s1 = 'S:\\problem\\file.docx'
>>> s2 = r'S:\problem\file.docx'
>>>
>>> len(s0), len(s1), len(s2)
(19, 20, 20)
>>>
>>> s0 == s1, s1 == s2
(False, True)
>>>
>>> repr(s0), repr(s1), repr(s2)
("'S:\\\\problem\\x0cile.docx'", "'S:\\\\problem\\\\file.docx'", "'S:\\\\problem\\\\file.docx'")

Replacing a specific part

I have a list like this:
DEL075MD1BWP30P140LVT
AN2D4BWP30P140LVT
INVD0P7BWP40P140
IND2D6BWP30P140LVT
I want to replace everything in between D and BWP with a *
How can I do that in unix and tcl
Do you have the whole list available at the same time, or are you getting one item at a time from somewhere?
Should all D-BWP groups be processed, or just one per item?
If just one per item, should it be the first or last (those are the easiest alternatives)?
Tcl REs don't have any lookbehind, which would have been nice here. But you can do without both lookbehinds and lookaheads if you capture the goalpost and paste them into the replacement as back references. The regular expression for the text between the goalposts should be [^DB]+, i.e. one or more of any text that doesn't include D or B (to make sure the match doesn't escape the goalposts and stick to other Ds or Bs in the text). So: {(D)[^DB]+(BWP)} (braces around the RE is usually a good idea).
If you have the whole list and want to process all groups, try this:
set result [regsub -all {(D)[^DB]+(BWP)} $lines {\1*\2}]
(If you can only work with one line at a time, it's basically the same, you just use a variable for a single line instead of a variable for the whole list. In the following examples, I use lmap to generate individual lines, which means I need to have the whole list anyway; this is just an example.)
Process just the first group in each line:
set result [lmap line $lines {
regsub {(D)[^DB]+(BWP)} $line {\1*\2}
}]
Process just the last group in each line:
set result [lmap line $lines {
regsub {(D)[^DB]+(BWP[^D]*)$} $line {\1*\2}
}]
The {(D)[^DB]+(BWP[^D]*)$} RE extends the right goalpost to ensure that there is no D (and hence possibly a new group) anywhere between the goalpost and the end of the string.
Documentation:
lmap (for Tcl 8.5),
lmap,
regsub,
set,
Syntax of Tcl regular expressions

Move file pointer to line with a known string in Python

I'm reading from a data file and I know my data begins after a line that contains '[Data]'.
I would like to search through the file until it reaches this line and then stops so I can begin to format the data. This is my attempt:
fid='myData.dat'
f=open(fid,'r')
fline = 'string'
while fline != '[Data]':
fline=f.readline()
print fline
However, it reads through every line in the document without stopping. I know for a fact that the line I want only contains [Data] and no other spaces or characters.
I'm sure there is a better way of doing this and I am open to going about this in any other way.
Probably '[Data]' is followed by a '\n' because it's the end fo the line, so you may try while fline != '[Data]\n':
If you are using Windows the newline characters will be "\r\n", '\n' is for Unix based systems.
The readline method return line with line endings:
while fline != '[Data]\n':
fline=f.readline()
You can strip white characters:
while fline.strip() != '[Data]':
fline=f.readline()
If you want no space before "[", you could remove them only on right side with .rstrip(). You can remove only line break with .rstrip("\r\n").

Simple Vim Programming (vimrc file)

I'm trying to learn how to configure my .vimrc file with my own functions.
I'd like to write a function that traverses every line in a file and counts the total number of characters, but ignores all whitespace. This is for a programming exercise and as a stepping stone to more complex programs (I know there are other ways to get this example value using Vim or external programs).
Here's what I have so far:
function countchars()
let line = 0
let count = 0
while line < line("$")
" update count here, don't count whitespace
let line = getline(".")
return count
endfun
What functional code could I replace that commented line with?
If I understand the question correctly, you're looking to count the number of non-whitespace characters in a line. A fairly simple way to do this is to remove the whitespace and look at the length of the resulting line. Therefore, something like this:
function! Countchars()
let l = 1
let char_count = 0
while l <= line("$")
let char_count += len(substitute(getline(l), '\s', '', 'g'))
let l += 1
endwhile
return char_count
endfunction
The key part of the answer to the question is the use of substitute. The command is:
substitute(expr,pattern,repl,flags)
expr in this case is getline(l) where l is the number of the line being iterated over. getline() returns the content of the line, so this is what is being parsed. The pattern is the regular expression \s which matches any single whitespace character. It is replaced with '', i.e. an empty string. The flag g makes it repeat the substitute as many times as whitespace is found on the line.
Once the substitution is complete, len() gives the number of non-whitespace characters and this is added to the current value of char_count with +=.
A few things that I've changed from your sample:
The function name starts with a capital letter (this is a requirement for user defined functions: see :help user-functions)
I've renamed count to char_count as you can't have a variable with the same name as a function and count() is a built-in function
Likewise for line: I renamed this to l
The first line in a file is line 1, not line 0, so I initialised l to 1
The while loop counted up to but not including the last line, I assume you wanted all the lines in the file (this is probably related to the line numbering starting at 1): I changed your code to use <= instead of <
Blocks aren't based on indentation in vim, so the while needs an endwhile
In your function, you have let line = getline('.')
I added a ! on the function definition as it makes incremental development much easier (everytime you re-source the file, it will override the function with the new version rather than spitting out an error message about it already existing).
Incrementing through the file works slightly differently...
In your function, you had let line = getline('.'). Ignoring the variable name, there are still some problems with this implementation. I think what you meant was let l = line('.'), which gives the line number of the current line. getline('.') gives the contents of the current line, so the comparison on the while line would be comparing the content of the current line with the number of the last line and this would fail. The other problem is that you're not actually moving through the file, so the current line would be whichever line you were on when you called the function and would never change, resulting in an infinite loop. I've replaced this with a simple += 1 to step through the file.
There are ways in which the current line would be a useful way to do this, for example if you were writing a function with that took a range of lines, but I think I've written enough for now and the above will hopefully get you going for now. There are plenty of people on stackoverflow to help with any issues anyway!
Have a look at:
:help usr_41.txt
:help function-list
:help user-functions
:help substitute()
along with the :help followed by the various things I used in the function (getline(), line(), let+= etc).
Hope that was helpful.
This approach uses lists:
function! Countchars()
let n = 0
for line in getline(1,line('$'))
let n += len(split(line,'\zs\s*'))
endfor
return n
endfunction
I suppose you have already found the solution.
Just for info:
I use this to count characters without spaces in Vim:
%s/\S/&/gn

How to check for and remove a newline (\n) in the first line of a text field in actionscript?

In the script, sometimes a newline is added in the beginning of the text field (am using a textArea in adobe flex 3), and later on that newline might need to be removed (after other text has been added). I was wondering how to check if there is a newline at the beginning of the text field and then how to remove it. Thanks in advance.
How about
private function lTrimTextArea(ta:TextArea) {
ta.text = ta.text.replace(/^\n*/,'');
}
To remove all line breaks from the start of a string, regardless of whether they are Windows (CRLF) or UNIX (LF only) line breaks, use:
ta.text = ta.text.replace(/^[\r\n]+/,'');
You should use + in the regex instead of * so that the regex only makes a replacement if there is actually a line break at the start of the string. If you use ^\n* as Robusto suggested the regex will find a zero-length match at the start of the string if the string does not start with a line break, and replace that with nothing. Replacing nothing with nothing is a waste of CPU cycles. It may not matter in this situation, but avoiding unintended zero-length matches is a very good habit when working with regular expressions. In other situations they will bite you.
If you particularly want to check first character here is solution:
if(ta.text.charAt(0) == "\n" || ta.text.charAt(0) == "\r")
{
ta.text.slice(1,ta.text.length-1);
}
slice method will slice that first character and gives your text from second character.
If you want to simply disable the ability to create a carriage return / new line, then all you need to do is disable multiline for that TextField...
(exampleTextField as TextField).multiline = false;
This will still trigger KEY_DOWN and KEY_UP events, however will not append the text with the carriage return.

Resources