print after a certain word in python - python

In Python, I would like to read the input and then only print after a certain point. I would like for it to work like this
humaninput = raw_input("Please enter:")
breakdown = humaninput.split()
say = "say"
if say in breakdown:
print (all words after say)
I have everything except for the last part

Here's a neat alternative that doesn't use split.
string = "string blah say foo bar"
say = "say"
after = string[string.index(say) + len(say):] # +1 if you're worried about spaces
print(after)
>> foo bar
And if there are multiple instances of "say", it will take the first.

Since you converted all the entries in to a list you can find the first instance of "say", then make a new list with everything after it.
humaninput = "This is me typing a whole bunch of say things with words after it"
breakdown = humaninput.split()
say = "say"
if say in breakdown:
split = breakdown.index(say)
after = breakdown[split+1:]
print(after)

This is pretty easy to do with split() if you're just using a string.
if say in humaninput:
saysplit = humaninput.split(say,1)
print saysplit[1]
It works on entire strings, not just single characters or nothing at all (where it defaults to space). If you've got a list, the other answer is correct.

Related

Can you cast a string to upper case while formating

Motivation
Suppose you have a string that is used twice in one string. However, in one case it is upper, and the other it is lower. If a dictionary is used, it would seem the solution would be to add a new element that is uppercase.
Suppose I have a python string ready to be formatted as:
string = "{a}_{b}_{c}_{a}"
With a desired output of:
HELLO_by_hi_hello
I also have a dictionary ready as:
dictionary = {a: "hello", b: "bye", c: "hi"}
Without interacting with the dictionary to set a new element d as being "HELLO" such as:
dictionary['d'] = dictionary['a'].upper()
string = "{d}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
Is there a way to set element a to always be uppercase in one case of the string? For example something like:
string= "{a:upper}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
Yes, you can do that:
string = "{d.upper()}_{b.lower()}_{c.lower()}_{a.lower()}"
Nope, you can't do that.
In the simplest solution, you can write a lambda to capitalize the values in your string. Or you can subclass strnig.Formatter if you really want to achieve your goal that way.
Following link can help if you are going for the harder method.
Python: Capitalize a word using string.format()

Python 3, receive a string as an argument without any return value

I'm learning Python and have been taking an online class. This class was very basic and I am know trying to continue my studies elsewhere. Stackoverflow.com has helped me a great deal. In the online course we didn't cover a lot about return statements, which I am now trying to learn. I would like to do something very basic, so I was thinking of creating a program that would receive a string as an argument without having any return value. I want the user to type a word that will be shown with characters or symbols between every letter.
Example
User types in the word Python.
The word will be shown as =P=y=t=h=o=n= or -P-y-t-h-o-n- or maybe with * between every letter.
Is this an easy task? Can someone help me how to go about doing this?
Thank you.
Joel
If you want to do it yourself, you can go through your string like this:
my_string = "Python"
for letter in my_string:
# do something with the letter
print(letter)
This will print each letter in your word. What you want to do is having a new string with your desired character. You probably know you can concatenate (append) two strings in this way :
str1 = "hello"
str2 = "world"
str3 = str1 + str2
print(str3) #helloworld
So to do what you'd like to do, you can see each letter as a substring of your main string, and your desired character (for example *) as another string, and build a result string in that way.
inputString = "Python"
result = ""
myChar = "*"
for letter in inputString:
# build your result
build = build + letter
print(build)
This will just copy inputString into result, though I think you'll have understood how to use it in order to add your custom chars between the letters.
Yes python makes this sort of string manipulation very easy (some other languages... not so much). Look up the standard join function in the python docs.
def fancy_print(s, join_char='-'):
# split string into a list of characters
letters = list(s)
# create joined string
output = join_char + join_char.join(letters) + join_char
# show it
print(output)
then
>>> fancy_print("PYTHON")
-P-Y-T-H-O-N-
>>> fancy_print("PYTHON", "*")
*P*Y*T*H*O*N*

replace multiple words - python

There can be an input "some word".
I want to replace this input with "<strong>some</strong> <strong>word</strong>" in some other text which contains this input
I am trying with this code:
input = "some word".split()
pattern = re.compile('(%s)' % input, re.IGNORECASE)
result = pattern.sub(r'<strong>\1</strong>',text)
but it is failing and i know why: i am wondering how to pass all elements of list input to compile() so that (%s) can catch each of them.
appreciate any help
The right approach, since you're already splitting the list, is to surround each item of the list directly (never using a regex at all):
sterm = "some word".split()
result = " ".join("<strong>%s</strong>" % w for w in sterm)
In case you're wondering, the pattern you were looking for was:
pattern = re.compile('(%s)' % '|'.join(sterm), re.IGNORECASE)
This works on your string because the regular expression would become
(some|word)
which means "matches some or matches word".
However, this is not a good approach as it does not work for all strings. For example, consider cases where one word contains another, such as
a banana and an apple
which becomes:
<strong>a</strong> <strong>banana</strong> <strong>a</strong>nd <strong>a</strong>n <strong>a</strong>pple
It looks like you're wanting to search for multiple words - this word or that word. Which means you need to separate your searches by |, like the script below:
import re
text = "some word many other words"
input = '|'.join('some word'.split())
pattern = re.compile('(%s)' % input, flags=0)
print pattern.sub(r'<strong>\1</strong>',text)
I'm not completely sure if I know what you're asking but if you want to pass all the elements of input in as parameters in the compile function call, you can just use *input instead of input. * will split the list into its elements. As an alternative, could't you just try joining the list with and adding at the beginning and at the end?
Alternatively, you can use the join operator with a list comprehension to create the intended result.
text = "some word many other words".split()
result = ' '.join(['<strong>'+i+'</strong>' for i in text])

How to pad a string to a fixed length with spaces in Python?

I'm sure this is covered in plenty of places, but I don't know the exact name of the action I'm trying to do so I can't really look it up. I've been reading an official Python book for 30 minutes trying to find out how to do this.
Problem: I need to put a string in a certain length "field".
For example, if the name field was 15 characters long, and my name was John, I would get "John" followed by 11 spaces to create the 15 character field.
I need this to work for any string put in for the variable "name".
I know it will likely be some form of formatting, but I can't find the exact way to do this. Help would be appreciated.
This is super simple with format:
>>> a = "John"
>>> "{:<15}".format(a)
'John '
You can use the ljust method on strings.
>>> name = 'John'
>>> name.ljust(15)
'John '
Note that if the name is longer than 15 characters, ljust won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:
>>> name.ljust(15)[:15]
If you have python version 3.6 or higher you can use f strings
>>> string = "John"
>>> f"{string:<15}"
'John '
Or if you'd like it to the left
>>> f"{string:>15}"
' John'
Centered
>>> f"{string:^15}"
' John '
For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax
You can use rjust and ljust functions to add specific characters before or after a string to reach a specific length.
The first parameter those methods is the total character number after transforming the string.
Right justified (add to the left)
numStr = '69'
numStr = numStr.rjust(5, '*')
The result is ***69
Left justified (add to the right)
And for the left:
numStr = '69'
numStr = numStr.ljust(3, '#')
The result will be 69#
Fill with Leading Zeros
Also to add zeros you can simply use:
numstr.zfill(8)
Which gives you 00000069 as the result.
string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces
This will add the number of spaces needed, provided the field has length >= the length of the name provided
name = "John" // your variable
result = (name+" ")[:15] # this adds 15 spaces to the "name"
# but cuts it at 15 characters
I know this is a bit of an old question, but I've ended up making my own little class for it.
Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:
2021-03-02 update: Improved a bit - when working through a large codebase, you know whether the line you are writing is one you care about or not, but you don't know what was previously written to the console and whether you want to retain it.
This update takes care of that, a class variable you update when writing to the console keeps track of whether the line you are currently writing is one you want to keep, or allow overwriting later on.
class consolePrinter():
'''
Class to write to the console
Objective is to make it easy to write to console, with user able to
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------
#Class variables
stringLen = 0
overwriteLine = False
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteThisLine=False):
import sys
#Get length of stringIn and update stringLen if needed
if len(stringIn) > consolePrinter.stringLen:
consolePrinter.stringLen = len(stringIn)+1
ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
prevOverwriteLine = consolePrinter.overwriteLine
if prevOverwriteLine:
#Previous line entry can be overwritten, so do so
sys.stdout.write("\r" + ctrlString.format(stringIn))
else:
#Previous line entry cannot be overwritten, take a new line
sys.stdout.write("\n" + stringIn)
sys.stdout.flush()
#Update the class variable for prevOverwriteLine
consolePrinter.overwriteLine = overwriteThisLine
return
Which then is called via:
consolePrinter.writeline("text here", True)
If you want this line to be overwriteable
consolePrinter.writeline("text here",False)
if you don't.
Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.
I generally recommend the f-string/format version, but sometimes you have a tuple, need, or want to use printf-style instead. I did this time and decided to use this:
>>> res = (1280, 720)
>>> '%04sx%04s' % res
'1280x 720'
Thought it was a touch more readable than the format version:
>>> f'{res[0]:>4}x{res[1]:>4}'
First check to see if the string's length needs to be shortened, then add spaces until it is as long as the field length.
fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
rand += " "
Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.
def format_string(str, min_length):
while len(str) < min_length:
str += " "
return str

Add characters (',') every time a certain character ( , )is encountered ? Python 2.7.3

Let's say you had a string
test = 'wow, hello, how, are, you, doing'
and you wanted
full_list = ['wow','hello','how','are','you','doing']
i know you would start out with an empty list:
empty_list = []
and would create a for loop to append the items into a list
i'm just confused on how to go about this,
I was trying something along the lines of:
for i in test:
if i == ',':
then I get stuck . . .
In Python, the nicest way to do what you want is
full_list = test.split(', ')
If your string might have some commas that aren't followed by spaces, you would need to do something a little more robust. Maybe
full_list = [x.lstrip() for x in test.split(',')]
>>> test = 'wow, hello, how, are, you, doing'
>>> full_list = test.replace(",","','")
>>> print full_list
wow',' hello',' how',' are',' you',' doing
i just added the flanking quotations manually

Categories