If the string is "43 Lobsters and 3 Crabs" I want to get only the s's from this string. There are three s's so in my new string I must have just "sss".
4 Answers
Try this:
>>> strng = '43 Lobsters and 3 Crabs'
>>> ''.join([letter for letter in strng if letter == 's'])
'sss'
Here we use a simple list comprehension to iterate through the string, and check if each letter matches the letter s
. This creates a list, and to make it into a string you just use the join
function.

- 100,794
- 21
- 241
- 231
why dont you use the count function?
thestr = "43 Lobsters and 3 Crabs"
y = 's'
x = thestr.count(y)
so now you know how many times it appears in the string use that variable to construct a string
finstr = y * x

- 3,628
- 1
- 12
- 19
-
1
-
1
-
To specifically construct the string, something like `'s'*string.count('s')` would work. – jayelm Sep 28 '14 at 23:51
-
-
Err, this answer doesn't actually full answer the question yet. You still need to incorporate JesseMu's suggestion in. – matsjoyce Sep 30 '14 at 20:03
You can try iterating over the characters of the string and if the character equals s, you take it to build a string. At the end the string would be "sss" if there were 3 's' in the string.

- 1,710
- 3
- 21
- 36
Have you tried anything so far?
Try a for loop:
One line (called "List Comprehension"):
input_string = "43 Lobsters and 3 Crabs" # Input line
answer = "".join(["s" for letter in input_string if letter == "s"])
# List comprehension
# "".join is to combine the list into a string
print (answer) # Output
# It is in parenthesis because I do not know your Python version
# Returns sss
Usual for loop:
input_string = "43 Lobsters and 3 Crabs" # Input line
answer = "" # Answer to which we will add "s"s as needed
for letter in input_string: # For loop
if letter == "s":
answer += "s" # Adding "s" to final if it is an "s"
print (answer) # Output
# Returns sss
If you want it to be case insensitive, add .lower()
to the input:
input_string = "43 Lobsters and 3 Crabs" # Input line
answer = "".join(["s" for letter in input_string.lower() if letter == "s"])
print (answer) # Output
# Returns sss regardless if it is capitalized or not
Or:
input_string = "43 Lobsters and 3 Crabs".lower() # Input line
answer = "".join(["s" for letter in input_string if letter == "s"])
print (answer) # Output
# Returns sss regardless if it is capitalized or not
And if you need to differentiate between capital and lowercase "s"s, try this.
I will use "43 LobsterS and 3 CrabS"
for input.
input_string = "43 LobsterS and 3 CrabS" # Input line
answer = ""
for letter in input_string:
if letter == "s":
answer += "s"
elif letter == "S":
answer += "S"
print (answer) # Output
# Returns sSS for "43 LobsterS and 3 CrabS"

- 308
- 4
- 13