Python - print split line starting at the n-th element - python

I have a string as the result of a line.split from a file.
How can I write this string to another file starting by the 5th element?
EDIT:
I got this and it works:
for line in data.readlines ()
if not line.startswith ("H"):
s = line.split ()
finaldata.write (" ".join (s [5:]))
finaldata.write ("\n")
The only problem is that i have some empty "cells" in my input and that is messing the output (shifting the data to the left where i the original input has a blank)
How can i do it?
Thanks!

To answer the original question: If you know the element by count you should slice the string. string[5:] would print the 5th character to the end of the line. Slicing has a pretty basic syntax; lets say you have a string
a = "a b c d e f g h"
You can slice "a" from the 5th character like this
>>> a[5:]
' d e f g h'
Slicing syntax is [start:end:step] . so [5:] says start at 5 and include the rest. There are a ton of examples here Understanding Python's slice notation
The second question isn't exactly clear what you're trying to achieve... Here are some examples of common standard string manipulations with inline comments
>>> a = "a b c d e f g h"
>>> a[5] # Access the 5th element of list using the string index
' '
>>> a[5:] # Slice the string from the 5th element to the end
' d e f g h'
>>> a[5::2] # Get every other character from the 5th element to the end
' '
>>> a[6::2] # Get every other character from the 6th element to the end
'defgh'
# Use a list comprehension to remove all spaces from a string
>>> "".join([char for char in a if char != " "])
'abcdefgh'
# remove all spaces and print from the fifth character
>>> "".join([char for char in a if char != " "])[5:]
'fgh'
>>> a.strip(" ") # Strip spaces from the beginning and end
'a b c d e f g h'
>>> a[5:].strip(" ") # slice and strip spaces from both sides
'd e f g h'
>>> a[5:].lstrip(" ") # slice and use a left strip
'd e f g h'
Edit: To add in a comment from another user. if you know the character rather than the position, you can slice from that. Though, if you have duplicate characters you'll have to be careful.
>>> a[a.index("e"):] # Slice from the index of character
'e f g h'
>>> b = "a e b c d e f g h e"
>>> b[b.index("e"):]
'e b c d e f g h e'

Related

how to add string in previous line to the end of next line in python

I want to add string startswith "AA" to the end of next line like this
(that have many lines in text)
input:
AA
1 A B C
2 D E F
AA
3 G H I
output:
1 A B C AA
2 D E F
3 G H I AA
you need to keep two lists, a temporary one to keep all your string that start with "AA" and other for the output and fill them accordingly
>>> text="""AA
1 A B C
2 D E F
AA
3 G H I"""
>>> output=[]
>>> temp=[]
>>> for line in text.splitlines():
line = line.strip() #remove trailing while spaces
if not line:
continue #ignore empty lines
if line.startswith("AA"):
temp.append(line)
else:
if temp: #concatenate our temp list if there anything there
line += " " + " ".join(temp)
temp.clear()
output.append(line)
>>> print("\n".join(output))
1 A B C AA
2 D E F
3 G H I AA
>>>
import sys # To use stdin(standard input) function
checker="AA" # Make var for chekcing word
raw=sys.stdin.readlines()
#paste text from clipboard and ctrl + z input
#If you takes too long time to paste text from clipboard
#Look below another code which to make lines list.
lines=list(map(str.strip,raw))
result=[]
for i in range(0,len(lines)-1):
if lines[i] == checker:
result.append(lines[i+1]+lines[i])
else:
pass
result_str='\n'.join(result)
print(result_str)
I hope it wiil work for you.
If your raw text's lines bigger than 1,000 than I reconnand you use open function. Here is some example.
your raw text file name is raw.txt and same folder with python file.
lines='' # Make empty str var
with open('raw.txt', 'r') as f:
lines=f.readlines(): # read all lines with escape code (\n)
Map=map(str.strip, lines) # remove escape code by map, strip function.
lises=list(Map) #to using slicing Map should transformed list.

How to add spaces in a string [duplicate]

This question already has answers here:
Efficient way to add spaces between characters in a string
(5 answers)
Closed 9 months ago.
I am using the python module, markovify. I want to make new words instead of making new sentences.
How can I make a function return an output like this?
spacer('Hello, world!') # Should return 'H e l l o , w o r l d !'
I tried the following,
def spacer(text):
for i in text:
text = text.replace(i, i + ' ')
return text
but it returned, 'H e l l o , w o r l d ! ' when I gave, 'Hello, world!'
You can use this one.
def spacer(string):
return ' '.join(string)
print(spacer('Hello,World'))
Or You can change this into.
def spacer(text):
out = ''
for i in text:
out+=i+' '
return out[:-1]
print(spacer("Hello, World"))
(If you want)
You could make the same function into a custom spacer function,
But here you also need to pass how many spaces(Default 1) you want in between.
def spacer(string,space=1):
return (space*' ').join(string)
print(spacer('Hello,World',space=1))
OR FOR CUSTOM SPACES.
def spacer(text,space=1):
out = ''
for i in text:
out+=i+' '*space
return out[:-(space>0) or len(out)]
print(spacer("Hello, World",space=1))
.→ OUTPUT.
H e l l o , W o r l d
The simplest method is probably
' '.join(string)
Since replace works on every instance of a character, you can do
s = set(string)
if ' ' in s:
string = string.replace(' ', ' ')
s.remove(' ')
for c in s:
string = string.replace(c, c + ' ')
if string:
string = string[:-1]
The issue with your original attempt is that you have ox2 and lx3 in your string. Replacing all 'l' with 'l ' leads to l . Similarly for o .
The simplest answer to this question would be to use this:-
"Hello world".replace("", " ")[1:-1]
This code reads as follows:-
Replace every empty substring with a space, and then trim off the trailing spaces.
print(" ".join('Hello, world!'))
Output
H e l l o , w o r l d !

Python, Slicing a string at intervals while keeping the spaces?

I need to select every third letter out of a sentence (starting from the first letter), and print out those letters with spaces in between them.
So it should look like this
Message? cxohawalkldflghemwnsegfaeap
c h a l l e n g e
or
Message? pbaynatnahproarnsm
p y t h o n
I've tried this:
nim = input("Line: ")[::+3]
and it works fine, but I have to keep the spaces between the letters.
Use str.join:
nim = ' '.join(input("Line: ")[::3])
# Line: pbaynatnahproarnsm
print(nim)
Output:
'p y t h o n'
If you want to just print the letters out of sentence with spaces between them, you can use sep= parameter of print() and asterisk *:
print(*input("Line: ")[::3], sep=' ')
Prints:
Line: cxohawalkldflghemwnsegfaeap
c h a l l e n g e

Python: add '\' to int in order to display a letter

The question is simple. I have a txt file with ASCII codes that I want to display as a readable English text. In order to do so, I've parsed it into a list of integers (let's call it l) with integers. so that '\l[0]' displays '*' if l[0] = 42.
What I have trouble doing is to add an escape to the integer, for instant '\' + 'l[0]' is invalid because Python understands as "I try to escape the quote but I couldn't find the ending quote" and if I do '\'+ 'l[0]', I'll indeed see '\42' on screen, because the first backslash escapes the second and there is no escaping in the last expression.
So the question is how could one add a backslash as escape character to another string?
Thanks a lot.
Once you have converted the ASCII codes to integers, just use chr to display them.
for c in l:
sys.stdout.write(chr(c))
I think you would find chr() built-in function useful.
If you have a list of integers you can directly display corresponding ascii characters using chr() method as:
>>> l=range(33,128)
>>> for i in l: print chr(i),
...
! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? # A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~
This way you don't need to add '\' to any integer to display its character.

Replacing all multispaces with single spaces

For example
s = "a b c d e f "
Needs to be reduced to
s = "a b c d e f "
Right now I do something like this
for i in xrange(arbitrarilyHighNumber,1,-1):
s = s.replace(" "*i," ")
But I want to make it more dynamic and Pythonic (and assume any number of spaces, too). How can I replace every contiguous space threshold with a single space?
You can use re.sub:
>>> import re
>>> s = "a b c d e f "
>>> re.sub('\s{2,}', ' ', s)
'a b c d e f '
>>>
\s{2,} matches two or more whitespace characters.
Since the regular expression answer has already been given. You could also do it with iterative replacements.
while s.find(" ") is not -1:
s = s.replace(" ", " ")
My original answer of splitting and rejoining gets rid of the leading and trailing whitespaces
' '.join(s.split())

Categories