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

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

Related

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 !

function to operate on all parts of string which don't match a regex pattern

Say I have a string:
"a bb c exclude_start d 3 f g h _ k l . exclude_end n 0 P exclude_start q r exclude_end s"
And say I would to apply an upper function which will return:
"A BB C exclude_start d 3 f g h _ k l . exclude_end N 0 P exclude_start q r exclude_end S"
I would like a solution which will allow for n number of excluded blocks and will apply the upper function only to the characters outside of these blocks.
It would be nice if there was a way to regex match only strings outside of the excludes, then only apply upper to these.
I'm not sure if there's a way to do this with a single regex, but here's my thought process for this. I figure we want to split the string apart so that we can capitalize only the parts that aren't in the exclude blocks. The way to do that would be to make a regex to match the exclude block:
>>> import re
>>> exclude_pattern = re.compile(r'(exclude_start.*?exclude_end)')
We need to include the question mark in there so that it doesn't match greedily.
Since we will want to keep the parts of the string that match our exclude_pattern instead of just throwing them out, we can use re.split:
If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.
which is why we need the parentheses in our exclude_pattern.
Next we want to split the string using that pattern:
>>> input_string = "a bb c exclude_start d 3 f g h _ k l . exclude_end n 0 P exclude_start q r exclude_end s"
>>> exclude_pattern.split(input_string)
['a bb c ', 'exclude_start d 3 f g h _ k l . exclude_end', ' n 0 P ', 'exclude_start q r exclude_end', ' s']
That gives us the separation we need.
The next thing we want is to upper only the strings that don't match our exclude pattern. For that I figure we can map a lambda over our list that checks each entry against our exclude pattern, and only uppers the ones that don't match:
>>> list(map(lambda s: s.upper() if not exclude_pattern.match(s) else s, exclude_pattern.split(input_string)))
['A BB C ', 'exclude_start d 3 f g h _ k l . exclude_end', ' N 0 P ', 'exclude_start q r exclude_end', ' S']
The list() is just so we can see what is in the resulting map object.
After that we just join it all back together:
>>> ''.join(map(lambda s: s.upper() if not exclude_pattern.match(s) else s, exclude_pattern.split(input_string)))
'A BB C exclude_start d 3 f g h _ k l . exclude_end N 0 P exclude_start q r exclude_end S'
If you'd rather not do it as a one-liner (it's a little gross), we can make it into a function:
def excluded_upper(input_string):
exclude_pattern = re.compile(r'(exclude_start.*?exclude_end)')
split_string = exclude_pattern.split(input_string)
output = []
for s in split_string:
if exclude_pattern.match(s):
output.append(s)
else:
output.append(s.upper())
return ''.join(output)

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

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'

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