How to switch \n to a newline in list? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
with open("C:\\test\\data1.txt") as f:
data = f.readlines()
tail = data[-10:]
I have a file name data1.txt inside folder test, when my program reads from the file it reads the whole content from the file and prints only the last 10 lines from the file.
['this is line number 21\n', 'this is line number 22\n', 'this is line
number 23\n', 'this is line number 24\n', 'this is line number 25\n',
'this is line number 26\n', 'this is line number 27\n', 'this is line
number 28\n', 'this is line number 29\n', 'this is line number 30\n']
I want to print the last 10 lines from the file with line breaks but cant figure how I can put inside a line break inside a list data structure.
for example :
To print txt file (data1.txt) like that :
this is line number 21
this is line number 22
this is line number 23
this is line number 24
without the \n and the list deceleration ([' '])

There are many answers already, but no one explained the problem.
Problem
\n is the newline character!
Explanation
In order to be able show the newline within a string literal, the escape sequence \n is used, e.g.:
>>> 'a\nb'
'a\nb'
>>> print('a\nb')
a
b
print function prints the string, if a string argument is passed to it, but if some other object is passed to it, it first has to be converted to a string, so print(x) is the same as print(str(x)).
When a list of strings is converted to string, that is done by calling repr on each of its items:
>>> ['a', 'a\nb']
['a', 'a\nb']
>>> str(['a', 'a\nb'])
"['a', 'a\\nb']"
>>> print("['a', 'a\\nb']")
['a', 'a\nb']
Solution
Now, if you want to print the last 10 lines, it means you should print each string in the list, not the list object itself, e.g.:
for s in list_of_strings:
print(s)
Now, since the s already contains a newline and print adds a newline itself, you should remove one of the newlines to make the solution complete:
for s in list_of_strings:
print(s.strip('\n'))
or:
for s in list_of_strings:
print(s, end='')
or create one string by concatenating items of the list and print that:
print(''.join(list_of_strings))

Best is a join (works on any version):
print(''.join(tail))

Just print tail like this:
print(*tail, sep='')
The sep argument stops the automatic space that is normally used as a separator between printed items.

Maybe this will help:
f.readlines()[-10:]
this way you will get last 10 lines.
Or just:
data = f.readlines()[-10:]
for d in data:
print(d) # will print everything on new line

Related

Python script search a text file for a word [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm writing a Python script. I need to search a text file for a word that end by " s , es or ies " and the word must be greater than three letters , need to konw number of words and the word it-self .....it's hard task i cant work with it, please help me
I agree with the comment that you need to go work on the basics. Here are some ideas to get you started.
1) You say "search a file." Open a file and read line by line like this:
with open ('myFile.txt', 'r') as infile:
for line in infile:
# do something to each line
2) You probably want to store each line in a data structure, like a list:
# before you open the file...
lines = []
# while handling the file:
lines.append(line)
3) You'll need to work with each word. look into the 'split' function of lists.
4) You'll need to look at individual letters of each word. Look into 'string slicing.'
All said and done, you can probably do this with 10 - 15 lines of code.
Try to divide the task into different tasks if it feels overwhelming.
The following code is by no means good, but hopefully it is clear enough so you can get the point.
1 First you need to get your text. If your text is in a file in your computer you need to put it into something that python can use.
# this code takes the content of "text.txt" and store it into my_text
with open("text.txt") as file:
my_text = file.read()
2 Now you need to work with every individual word. All your words are together in a string called my_text, and you would like them separated (split) into a list so you can work with them individually. Usually words are separated by spaces, so that's what you use to separate them:
# take the text and split it into words
my_words = my_text.split(" ")
3 I don't know exactly what you want, but let's suppose you want to store separately the words in different lists. Then you will need those lists:
# three list to store the words:
words_s = []
words_es = []
words_ies = []
4 Now you need to iterate through the words and do stuff with them. For that the easiest thing to do is to use a for loop:
#iterate through each word
for word in my_words:
# you're not interested in short words:
if len(word) <= 3:
continue # this means: do nothing with this word
# now, if the word's length is greater than 3, you classify it:
if word.endswith("ies"):
words_ies.append(word) # add it to the list
if word.endswith("es"):
words_es.append(word) # add it to the list
if word.endswith("s"):
words_s.append(word) # add it to the list
4 Finally, outside the for loop, you can print the list of words and also get the length of the list:
print(words_s)
print(len(words_s))
Something that you need to consider is if you want the words repeated or not. Note that the condition 'word that end by "s", "es" or "ies"' is equivalent to 'word that end by "s"'. The code above will get the words distributed in different lists redundantly. If a word ends with "ies" it also ends with "es" and "s", so it'll be stored in the three lists. If you want to avoid overlapping, you can substitute the if statements by else if statements.
Keep learning the basics as other answers suggest and soon you'll be able to understand scary code like this :D
with open("text.txt") as myfile:
words = [word for word in myfile.read().split(" ") if word.endswith("s") and len(word) > 3]
print("There are {} words ending with 's' and longer than 3".format(len(words)))

Split String into groups [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I've a string like this Delete File/Folder. I need to break the sentence based on the / equivalent to or.
Finally need to generate two strings out of this like Delete File as one string and Delete Folder as the other one.
I've tried very naive way where I check for the index of / and then form strings with a bunch of conditions.
It some times fails when we have string like File/Folder Deleted.
Edit:
If you split on / then for case 1 we have Delete File and Folder. Then I'll check for spaces present in first string and spaces present is second string.
The one which has less number of spaces will be replaced with first string last element. This is getting complicated.
In the case of Delete File/Folder, thinking through why the word Delete gets distributed to both of File and Folder might help with the inherent assumptions we all intuitively make when lexical parsing.
For instance, it would be parsed between the the i and l to return ["Delete File", "Delete FiFolder"].
It sounds like you want to want to split the string into words based on where there are spaces and then split each word based on / to generate new full strings.
>>> import itertools
>>> my_str = "Delete File/Folder"
>>> my_str = ' '.join(my_str.split()).replace('/ ', '/').replace(' /', '/') # First clean string to ensure there aren't spaces around `/`
>>> word_groups = [word.split('/') for word in my_str.split(' ')]
>>> print [' '.join(words) for words in itertools.product(*word_groups)]
['Delete File', 'Delete Folder']
Do you want that? Comment if you want a more generalized solution.
lst = your_string.split()[1].split("/")
finalList=[]
for i in lst:
finalList.append("Delete {0}",i)
print finalList
For string:
Delete File/Folder
Output:
['Delete File', 'Delete Folder']
str = "Do you want to Delete File/Folder?"
word = str.split(" ")
count = str.count("/")
c = True
for j in range(0,2*count):
for i in word:
if("/" in i):
words = i.split("/")
if c:
print words[1],
else:
print words[0],
else:
print i, # comma not to separate line
c = not c
print
output
Do you want to Delete File
Do you want to Delete Folder?
st1 = "Do you want to Delete File/Folder"
st2 = "File/Folder Updated"
def spl(st):
import re
li = []
ff = re.search(r'\w+/\w+',st).group()
if ff:
t = ff.split('/')
l = re.split(ff,st)
for el in t:
if not l[0]:
li.append((el + ''.join(l)))
else:
li.append((''.join(l) + el))
return li
for item in st1,st2:
print(spl(item))
['Do you want to Delete File', 'Do you want to Delete Folder']
['File Updated', 'Folder Updated']

Formatting a line with spaces at the beginning

Consider below piece of code
line = "I am writing a question"
print('{0: >10}'.format(line))
This does not work as expected. I expected output to be
' I am writing a question'
I know I can achieve this by other means like printing the spaces first using one print statement and then print the sentence. But curious to know what I might be doing wrong.
Your line is longer than 10 characters; the width is a minimal value and applies to the whole column. If you wanted to add 10 spaces, always, prefix these before the format:
print(' {0}'.format(line))
If you always wanted to right-align the string in a column of 33 characters (10 spaces and 23 characters for your current line), then set the column width to that instead:
print('{0:>33}'.format(line))
Now, when your line value is longer or shorter, the amount of whitespace will be adjusted to make the output 33 characters wide again.
Demo:
>>> line = "I am writing a question"
>>> print(' {0}'.format(line))
I am writing a question
>>> print('{0:>33}'.format(line))
I am writing a question
>>> line = "question"
>>> print('{0:>33}'.format(line))
question
There is a built in method :
https://docs.python.org/2/library/stdtypes.html#str.rjust
v = 'hi'
print v.rjust(4, ' ');
prints
' hi'

join python array after splitting from given index [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a python string called line that I've split. line is a recurring string. I'm searching through an excel file and printing out each line that contains a specific word, i'll call it search which is a term that the user inputs. If the line doesn't contain search then it doesn't get printed.
I split the line, and printed out the search_index (index of the search term in the line).
s=line.split()
search_index = s.index(search) if inflected in s else "not in this line"
print(search_index)
If it doesn't exist in the line then the log will say "not in this line" instead of a number since it was crashing whe nI didn't include that.
What I awnt to do is join this split back together, but from a range with the searched term being teh middle. So, something like
new_line=[search_index - 5:search_index + 5]
but not sure if that's right since it gives me an error on the webpage of "syntax invalid"
How should this be properly done?
I think you have a typo (missing line before your range [:]) but there's another thing as well. If your search_index has been assigned a string, you can't subtract or add 5 to it.
I'm not sure of the context so you'll have to tweak this to your needs but this addresses those issues:
s=line.split()
if inflected in s:
search_index = s.index(search)
new_line = line[search_index-5:search_index+5]
else:
print("not in this line")
When you get the attribute of a list, you always have to put the name of the list before how you are calling it:
>>> line = 'hello world!'
>>> search_index = 3
>>> [search_index-3:search_index+3]
File "<stdin>", line 1
[search_index-3:search_index+3]
^
SyntaxError: invalid syntax
>>> line[search_index-3:search_index+3]
'hello '
>>>
Therefore, instead of new_line = [search_index-5:search_index+5], use new_line = line[search_index-5:search_index+5].
Here is another example:
>>> line = 'Hello this is django on python'
>>> line = line.split()
>>> search_index = line.index('django')
>>> new_line = [search_index - 2:search_index + 2]
File "<stdin>", line 1
new_line = [search_index - 2:search_index + 2]
^
SyntaxError: invalid syntax
>>> new_line = line[search_index - 2:search_index + 2]
>>> new_line
['this', 'is', 'django', 'on']
>>>

Reading two strings from file

I'm writing a program in python and I want to compare two strings that exist in a text file and are separated by a new line character. How can I read the file in and set each string to a different variable. i.e string1 and string2?
Right now I'm using:
file = open("text.txt").read();
but this gives me extra content and not just the strings. I'm not sure what it is returning but this text file just contains two strings. I tried using other methods such as ..read().splitlines() but this did not yield the result I'm looking for. I'm new to python so any help would be appreciated!
This only reads the first 2 lines, strips off the newline char at the end, and stores them in 2 separate variables. It does not read in the entire file just to get the first 2 strings in it.
with open('text.txt') as f:
word1 = f.readline().strip()
word2 = f.readline().strip()
print word1, word2
# now you can compare word1 and word2 if you like
text.txt:
foo
bar
asdijaiojsd
asdiaooiasd
Output:
foo bar
EDIT: to make it work with any number of newlines or whitespace:
with open('text.txt') as f:
# sequence of all words in all lines
words = (word for line in f for word in line.split())
# consume the first 2 items from the words sequence
word1 = next(words)
word2 = next(words)
I've verified this to work reliably with various "non-clean" contents of text.txt.
Note: I'm using generator expressions which are like lazy lists so as to avoid reading more than the needed amount of data. Generator expressions are otherwise equivalent to list comprehensions except they produce items in the sequence lazily, i.e. as just as much as asked.
with open('text.txt') as f:
lines = [line.strip() for line in f]
print lines[0] == lines[1]
I'm not sure what it is returning but this text file just contains two strings.
Your problem is likely related to whitespace characters (most common being carriage return, linefeed/newline, space and tab). So if you tried to compare your string1 to 'expectedvalue' and it fails, it's likely because of the newline itself.
Try this: print the length of each string then print each of the actual bytes in each string to see why the comparison fails.
For example:
>>> print len(string1), len(expected)
4 3
>>> for got_character, expected_character in zip(string1, expected):
... print 'got "{}" ({}), but expected "{}" ({})'.format(got_character, ord(got_character), expected_character, ord(expected_character))
...
got " " (32), but expected "f" (102)
got "f" (102), but expected "o" (111)
got "o" (111), but expected "o" (111)
If that's your problem, then you should strip off the leading and trailing whitespace and then execute the comparison:
>>> string1 = string1.strip()
>>> string1 == expected
True
If you're on a unix-like system, you'll probably have an xxd or od binary available to dump a more detailed representation of the file. If you're using windows, you can download many different "hex editor" programs to do the same.

Categories

Resources