using .find to find the space in a line Python - python

im currently using this code
position= line.find(" ")
to help me find a position for example in the case of a name: Coner John Smith
how do i single out the smith, currently my line of code wont help because it positions itself on the first space it finds, how do rewrite the code to find the second space in a line?

Use find() twice:
firstspace = line.find(" ")
if firstspace != -1:
secondspace = line.find(" ", firstspace+1)
The second argument to str.find() is the position to start searching from.

The answer to your literal question is:
position= line.find(" ", line.find(" ") + 1)
What this does is find the first space in line, and then find the first space in line, starting the search on the position of the first space, plus one. Giving you the position of the second space.
But as #barmar points out, this is probably an example of an XY problem
Do you want the second space? Or the last space (e.g. 'Mary Jo Suzy Smith')?
Do you want the position of the space? Or are you really just after the last word in the string? Do you care about any interpunction following the last word in the string (e.g. 'John Smith!')
Every case has a slightly different better answer.
To get the last word, you could:
last_word = line.split(' ')[-1]
To find the last space, if you need it for something else:
last_space = line.rfind(' ')
Etc.

If you want the last space, use rfind or if you really want the last word, .rsplit() for it
>>> "Coner John Smith".rfind(" ")
10
>>> "Coner John Smith".rsplit(" ", 1)[-1]
'Smith'
If you want the Nth space, you can repeatedly locate with .find(), which can accept a start arg for where to begin finding!
source_text = "Coner John Smith"
N = 2
index = -1 # search from index 0
for _ in range(N):
index = source_text.find(" ", index + 1)
# opportunity to discover if missing or `break` on last, etc.

Related

Python exercise, guidance for slicing substrings

Please write a program which asks the user to type in a string. The program then prints out all the substrings which begin with the first character, from the shortest to the longest. Have a look at the example below.
Please type in a string: test
t
te
tes
test
Obviously my code is not the way it supposed to be:
stg = input("Please type in a string: ")
print(stg[0])
print(stg[0:5])
print(stg[0:10])
print(stg[10:50])
print(stg[:])
ok, this is a homework and I don't give you the exact solution... but as some points:
you have a string and want to print first 1 letter, first 2 letters and so on... so your range end must increase one by one...
you don't know about input length so you can't use hard code and use a loop
for loop you need to know about string length and use a builtin method for getting the length...
any question? ask it...
userString = input("Gimme String: ")
# Looping based on the given String
# Last Value is not included so you need to increment the value by one
for i in range(len(userString)):
# Last Value is not included so you need to increment the value by one
print(userString[:i+1])
#Alternative
for i in range(1,len(userString)+1):
print(userString[:i])
stg = input("Please type in a string: ")
print("\n".join([stg[0:i+1] for i in range (len(stg))]))
Output:
t
te
tes
test
Just use simple for loop
stg = 'test'
temp_str = ''
for i in range(len(stg)):
temp_str = temp_str + stg[i]
print(temp_str)

Finding the index of a common character in a for loop

First of all I know this is probably a [duplicate] but I could not find the answer to my question specifically anywhere.
I have a string generated by the user that I want my program to iterate over. Everything goes fine except for the fact that because I'm trying to access the index of a character " " (space) which appears more than once, whenever I try getting the index of the newly assigned space value for " ", it automatically gives me the index of the first " " in the string. I want this program to differentiate between words and create a list with the words in the string using a space to distinguish between them. What am I doing wrong?
list_words=[]
def findwords(sentence):
index1=0
index2=0
for space in sentence:
if space==" ":
index1=sentence.index(space)
list_words.append(sentence[index2:index1])
index2=index1
print(list_words)
findwords("What is your name?")
If you want a list of words, then use the API that was designed for that purpose:
def findwords(sentence):
return sentence.split()
print(findwords("What is your name?"))
As #Tim Roberts mentioned, you can simply use sentence.split(" ") to retrieve a list of words in the sentence split by a space. This function creates a list that has elements as words of the sentence that are divided by a " ".
However, using your code, we can edit it so that after we find a space, we add the previous word to the list and we edit sentence so that it does not contain the previous word or space. After we reach the end of the sentence, since there is no space ending the sentence, after the for loop, we should add whatever word is left in our sentence to the list.
Remember to use a copy of sentence to iterate as we should not modify whatever we are iterating. This code is built off of your code and produces the same output as using sentence.split(" "):
list_words=[]
def findwords(sentence):
sent = sentence
for space in sent:
if space == " ":
index1=sentence.index(space)
list_words.append(sentence[0:index1 + 1])
sentence = sentence[index1 + 1:]
list_words.append(sentence)
findwords("What is your name?")
print(list_words)
Output:
['What ', 'is ', 'your ', 'name?']
I hope this helped answer your question! Let me know if you need any further details or clarification :)

Which index of string is an int in python

I am reading a text file with high scores and trying to find which index of the string is where the name stops, and the score starts. This is the format of the file:
John 15
bob 27
mary 72
videogameplayer99 99
guest 71
How can I do this?
If you are looking to find the index to split the string into 2 separate parts, then you can just use [string].split() (where string is an individual line). If you need to find the index of the space for some other reason, use: [string].index(" ").
You can strip the line to separate it by the space. It will result in a list containing the 2 'words' in the line, in this case the words will be the name and the score (in string). You can get it using:
result = line.split()
name = result[0]
score = int(result[1])
In this case, for each line, you would be looking for the index where you first find the space character " ". In python, you can accomplish this by using the find function on a string. For example, if you have a string s = videogameplayer99 99, then s.find(" ") will return `17'.
If you are using this method to split a name from a number, I would instead recommend using the split function, which will split a string based on some delimiter character. For example, s.split(" ") = ["videogameplayer99", "99"].

How to get the first character of a string?

I need help to see what is wrong with my code; I'm getting the incorrect output.
I need the output to print the first initial and last name (with a period . in front of the first initial), for example: "Anna Lockswell" should be printed as "A. Lockswell".
So far I have:
firstName = input("What is your first name? ")
lastName = input("What is your last name? ")
str(print(firstname[0:-1], +lastname))
Welcome to programming! There are a few issues with what you've posted. First, let's try to get the first letter of firstname:
firstname = input("What is your first name? ")
# firstname is a string, where each letter acts like an element in an array
# to get the first letter, do this:
first_initial = firstname[0]
Per Micha's suggestion, the reason I'm using firstname[0] is because I only want the first letter. The slice firstname[0:-1] will give you everything except the last letter, which isn't quite what you want.
Now, you already have your lastName, next to print.
You have str(print("thing to print")). The problem here is print is a function which doesn't return anything. By wrapping that in str you will see the output None. To print, just call print:
print(first_initial + '.' + ' ' + lastName)
You will need to add a space to the printed output to space out the initial and the last name. There are fancier and more pythonic ways to print, but I feel that this is a sufficient place to start
here are a few things that need attention:
when you write firstname[a:b] it'll return the value of
firstname from char a to char b. so when your firstname is
"anna" and you'll type firstname[1:3] you'll get 'nn'. in this case minus one is equal to the index of the last character which is 3. so firstname[0:-1] will return "ann". in your case it should be changed to firstname[0].
str in the last line is completely unnecessary. str is used for converting other types to string. for example str(1) returns '1'.
print(a,b) will print 2 3 assuming a = 2 and b = 3 so you'll need to use print( a + '.' + b) for getting 2.3. ( there are many other ways to do this).
Try any of these:
>>> print('{}. {}'.format(firstname[0], lastname))
A. Lockswell
>>> print(firstname[0] + '. ' + lastname)
A. Lockswell
>>> print(f'{firstname[0]}. {lastname}')
A. Lockswell

Write programs that read a line of input as a string and print every second letter of the string in Python

Write programs that read a line of input as a string and print every second letter of the string in Python?
So far I have written:
string=input('Enter String: ')
for char in range(0,len(string),2):
print(len(char))
if i input a string: qwerty
it should print "qet"
You need to keep it much simpler than this. If you enter a word and are looking to slice it at a specific point, use slicing.
Your criteria: qwerty it should print "qet"
So, you are looking to print every second letter:
>>> a = "querty"
>>> a[::2]
'qet'
Slicing works like this:
[from start: from end: step]
So, in your case, you are looking to simply print every second, so you want to make use of your step. So, simply slice leaving the start and end empty, since you want to position yourself at the beginning of the string and then simply go every second. This is the reasoning behind using [::2]
Every second letter should start with index of 1 not 0. So, if your input is "qwerty", you output should be "wry".
Code below may be able to answer your question.
sentence = input("\nPlease enter a string : ")
print("Every second letter of the string " + sentence + " is ", end="")
for i in range(len(sentence)):
if i % 2 == 1:
print(sentence[i] + " ", end="")

Categories